JavaScript - append() not appending a button, but text

2.3k views Asked by At

Example:

var buttonHTML = "<button>MyButton</button>";
document.getElementById("myDiv").append(buttonHTML);

In this case, the function ends up appending the text into the div.

However, if I do the same with JQ:

$("#myDiv").append(buttonHTML);

In this case it will actually append the button. Now, for various reasons, I have to use plain JS (not JQ).

Anyone have any ideas?

3

There are 3 answers

0
Neri Barakat On

I am not sure how it worked with you and appended the element as text here, because there is no .append function in pure JS

But I agree with what @Sam Judge said in his answer,and also want to mention that you can do it using javascript without creating nodes one by one using javascript function Element.insertAdjacentHTML()

insertAdjacentHTML() parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position. It does not reparse the element it is being used on and thus it does not corrupt the existing elements inside the element. This avoiding the extra step of serialization make it much faster than direct innerHTML manipulation.

And there is another option to do the same using the .innerHTML but for sure you will need to save what's already inside to do the append effect.

3
ZombieTfk On

This is because your var buttonHTML is just a string of text, if you append it as a child, it will create a DOM textNode, rather than an elementNode. What you want to do instead is something along the lines of the following :

var buttonHTML = document.createElement("button");
var buttonText = document.createTextNode("MyButton");
buttonHTML.appendChild(buttonText);

document.getElementById("myDiv").appendChild(buttonHTML)
0
Khuram Shahzad On

you can try this code

function myFunction() {
  var myButton= document.createElement("button");
  myButton.style.width = "100px";
  myButton.style.height = "30px";
  myButton.style.background = "grey";
  myButton.style.color = "white";
  myButton.innerHTML = "MyButton";

  document.getElementById("demo1").appendChild(myButton);
}
<button type="button" onclick="myFunction()">create another button</button>

<p id="demo1"></p>