Good afternoon, javascript experts. Is there any difference in adding elements via innerHTML or appendChild ? I have long lines to add, for example

 <tr><td><img class='button' alt='delete'></td></tr> 

Since this is a single page application, there is a possibility that the newly added elements will have to be accessed (hang handlers, delete, and so on). When added via appendChild this naturally takes a lot of lines of code and the readability of the code drops. If you just add it using template strings, readability will increase. Are there any pitfalls?

  • Is there any difference in adding elements via innerHTML or appendChild? - principled! - Grundy

1 answer 1

The difference between these functions is fundamental. They do completely different things.

.innerHtml

It is a rule that removes all of the elements.

Deletes all child elements, parses the resulting string and adds the result as child elements.


.appendChild

The Node.appendChild () method adds the node.

The Node.appendChild() method adds a node to the end of the list of child nodes.

  • So it is important :) - user207618
  • I formulated the problem a bit wrong: 1. I first create createElement ('tr'). Then I stuff td-shki into it. I can type through createElement, then appendChild. I can through innerHTML. At the end of the new line, naturally I add to the end of the existing lines, i.e. appendChild. The question is, after creating tr, how best to fill it with td-shki, in terms of performance, accuracy and so on. - Tobakalov Kaniet
  • To avoid being stupid, I'll show you right away: there is such a table: habrastorage.org/web/ed3/309/28b / ... Actually, I need to add a new line to it. How to do it better: appendChild or innerHTML. - Tobakalov Kaniet
  • @Aid, of course, a full cycle of purification and analysis, instead of a single insert operation :) - Grundy
  • @ TobakalovKaniet, better is a relative concept: if you have a new element and you want to fill it, then there may be no difference (perhaps in performance, but you need to try hard to make it noticeable) - Grundy