0

Imagine, there is a larger website that accepts user interactions and needs to show a lot of new elements and delete other ones when the user clicks somewhere.

Can there be a significant performance difference these 2 approaches?


putting everything in a string:

var x = document.getElementByID("x");
x.innerHTML = "<div><div><span>...</span><div>...</div></div></div>"` 

writing the hierarchy like this:

var a = document.createElement("div");
var b = document.createElement("div");
var c = document.createElement("span");
// ...
a.appendChild(b)
b.appendChild(c)
// ...
var x = document.getElementByID("x");
document.body.insertBefore(a, x); 
hardfork
  • 2,470
  • 1
  • 23
  • 43
  • 1
    Possible duplicate of [Advantages of createElement over innerHTML?](https://stackoverflow.com/questions/2946656/advantages-of-createelement-over-innerhtml) – Seblor Mar 08 '19 at 08:05
  • updating DOM as little as possible is the right way – Kajbo Mar 08 '19 at 08:13
  • To add to the above commenters, generally they should be pretty close in speed for normal applications in modern browsers. Some old browsers (e.g. older versions of IE) were significantly faster with innerHTML. I would recommend not using innerHTML, among other things it can leave you vulnerable to XSS if you're not very careful. – Joru Mar 11 '19 at 22:57

0 Answers0