-1

Why do we use DOM to add elements (document.createElement("div");) to add elements, when we can add the element by using innerHTML for that parent element. I thought that it may be related to binding of events, but that’s also not the case. I read the theory of DOM and creating elements, but didn’t understand it. Can anyone explain it in a better way?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Purushottam zende
  • 552
  • 1
  • 6
  • 20
  • What is the “theory of DOM and creating elements”? Do you have a link to it? Otherwise we don’t know what exactly you didn’t understand and what precisely to explain better. – Sebastian Simon Jan 11 '17 at 06:15
  • 1
    Possible duplicate of [Advantages of createElement over innerHTML?](http://stackoverflow.com/questions/2946656/advantages-of-createelement-over-innerhtml) – Sebastian Simon Jan 11 '17 at 06:16

1 Answers1

0

Because often you want to creste elements with attribues , add styles etc ... and when you do this with innerHTML

var a = document.createElement('div');
a.setAttribute('class', 'red');
a.addEventListener('click',callback);

At the en of the day you hav much cleaner better maintainable code. And you dont need to access the dom more then once .... because imteracting with the dom is slow.

Simon Müller
  • 451
  • 1
  • 4
  • 17