Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DOM Element Creation vs. .innerHTML vs. Direct

Tags:

javascript

When generating dynamic content, which way is better to simply create the HTML and insert it into a .innerHTML or to create elements in the DOM directly?

I'm not concerned with complexity or other. Just processing time on the client.

Which is quicker?

If I had to guess in order of efficiency (low processing time) this would be:

  1. DOM Creation
  2. .innerHTML property insertion
  3. direct writing

This would be inversely related to the complexity of implmenting:

  1. direct writing
  2. .innerHTML property insertion
  3. DOM Creation

This is a validatin question? Can someone validate that this is the trade-offs for determining how to update the client (i.e. javascript) when considering complexity and speed?

Research:

I'm not concerned with security like they are here-> InnerHTML vs. DOM - Security

InnerHTML vs. DOM This is not a duplicate as it covers only part of my question.


1 Answers

In my experience they are basically comparable in performance. However if you use the DOM approach you get better accessibility to the power of closures so you can bind data and functions to the individual DOM elements directly.

For performance, the main thing, regardless of approach, is to hide or remove the part of the DOM you want to modified, make all you alterations outside the DOM, then put it back into the DOM as one single operation to avoid unnecessary reflows (repaints) in the browser.

like image 175
b-h- Avatar answered Oct 26 '25 05:10

b-h-



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!