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.
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:
...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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With