I want to create an HTML section using JavaScript, so I have two options:
I can create HTML elements using createElement() function:
document.createElement('div');
I can directly create elements like "<div>Test</div>" as a string.
Which one is better in performance?
Using the DOM API directly is much faster since it does not have to invoke the HTML parser.
var div = document.createElement("div");
container.appendChild(div);
Is considerably faster than
container.innerHTML += "<div></div>";
However, in most cases unless you're doing performance sensitive things, use the one that creates more readable code.
Is a bit off topic, but I think is a important point if anyone is going to use innerHTML
This is very wrong:
container.innerHTML = "<div>";
container.innerHTML += "Hello ";
container.innerHTML += "World";
container.innerHTML += "</div>";
If you really need to make up the string, only append it when the html is completed, you don't want to invoke the parser multiple times with incomplete html.
var html;
html = "<div>";
html += "Hello ";
html += "World";
html += "</div>";
container.innerHTML = html;
Another point is that innerHTML will parse everything again and will remove any event handlers attached to the elements inside a container.
container.innerHTML += moreContent; //previous content lost their event handlers
With DOM you don't need to worry about it, only the new content will be parsed.
container.appendChild(moreContent);
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