Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the performance cosiderations when creating HTML elements from JavaScript?

I want to create an HTML section using JavaScript, so I have two options:

  1. I can create HTML elements using createElement() function:

    document.createElement('div');
    
  2. I can directly create elements like "<div>Test</div>" as a string.

Which one is better in performance?

like image 696
Ankit Gupta Avatar asked Jun 17 '26 19:06

Ankit Gupta


2 Answers

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.

like image 133
Benjamin Gruenbaum Avatar answered Jun 19 '26 07:06

Benjamin Gruenbaum


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);
like image 37
Vitim.us Avatar answered Jun 19 '26 07:06

Vitim.us



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!