Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'appending' in Javascript

I am trying to learn JS without the use of a framework. Just a little doubt with the following:

<div class="js-button"></div>

In jQuery I can create a submit button with:

$("<button type='submit'>Save</button>").appendTo($(".js-button"));

In plain JS I could do:

document.querySelector(".js-button").innerHTML += "<button type='submit'>Save</button>";

This is exactly the same, right? Are there other ways to do this? If you happen to make the mistake of writing = istead of += you can expect big problems which I try to avoid.

like image 632
Dirk J. Faber Avatar asked Mar 05 '23 08:03

Dirk J. Faber


1 Answers

This is exactly the same, right?

No, not at all, though it's easy to see why you'd think that. It's almost never correct to use += with innerHTML. Doing so forces the browser to:

  • Spin through the element's contents building an HTML string
  • Append your string to that string
  • Destroy all of the contents of the element
  • Parse the string to build new contents, putting them in the element

...which aside from being a fair bit of unnecessary work also loses event handlers, the checked state of checkboxes/radio buttons, the selected options in select elements, etc.

Instead, use insertAdjacentHTML or createElement/createTextNode and appendChild. See the DOM on MDN. In that specific example:

document.querySelector(".js-button").insertAdjacentHTML(
    "beforeend",
    "<button type='submit'>Save</button>"
);
<div class="js-button"></div>
like image 157
T.J. Crowder Avatar answered Mar 13 '23 01:03

T.J. Crowder