Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 246
Mi Tim Avatar asked Oct 29 '22 14:10

Mi Tim


1 Answers

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.

like image 99
Neri Barakat Avatar answered Nov 15 '22 06:11

Neri Barakat