-1

Suppose I want to do this:

let el = document.getElementById("some_div");
el.innerHTML = "<div><h3>Hello There</h3><div>Hello World</div></div>";

Would it be better to write it as:

let outer_div = document.createElement("div");

let h3 = document.createElement("h3");

let inner_div = document.createElement("div");

let hello = document.createTextNode("Hello World");

inner_div.appendChild(hello);
outer_div.appendChild(h3);
outer_div.appendChild(inner_div);

Or does it not even matter coding wise in todays' environments?

mardubbles
  • 129
  • 6
  • Its 2022 use a framework and let the builder generate createElement's for your dom – Lawrence Cherone Mar 31 '22 at 21:43
  • 2
    FWIW, in your specific example [innerHTML is ~50% slower](https://jsbench.me/j3l1fiw260/1) than createElement in my [quick jsbench test](https://jsbench.me/j3l1fiw260/1). Note: both are extremely fast, so unless you're doing thousands of these it's probably not going to be noticeable and performance considerations should probably be secondary. – ray Mar 31 '22 at 21:44

1 Answers1

0

I suggest to use createElement. It is faster and more secure. Imagine you load user input directly into your DOM with innerHTML. This can be a nasty security hole.

Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
  • 1
    Ahh, security I didnt think of. Thank you. – mardubbles Mar 31 '22 at 21:36
  • 1
    "It is faster" Do you have any data to back that assertion up? @mardubbles Be careful about taking the word of random people on the internet at face value... – Heretic Monkey Mar 31 '22 at 21:40
  • 2
    @HereticMonkey If you insert HTML elements with innerHTML, you force the browser to analyse and regenerate all new DOM nodes within the main node. Whereas a created element does not entail the analysis. Therefore faster. And right, you should not believe strangers from the internet! – Maik Lowrey Mar 31 '22 at 21:45