Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between .insertAdjacentHTML and .innerHTML? [closed]

Tags:

javascript

What are differences to consider when choosing between the .insertAdjacentHTML and .innerHTML methods? What are compelling use-cases for each? Which has better performance and in what situations? How does .innerHTML work? Are there other alternatives?

like image 774
Azrael Avatar asked Jun 26 '26 10:06

Azrael


1 Answers

There are a few benefits .insertAdjacentHTML has over .innerHTML. The first of which is performance. In a benchmarking test performed, .innerHTML appended slightly over 200 Twitter tweets in five full seconds. insertAdjacentHTML, on the other hand appended nearly 30,000 in the same time-frame. The more data that needed to be appended, the worse .innerHTML performed. Note however, in this case, data was appended using .innerHTML +=.

Another benefit is control. .insertAdjacentHTML provides you with control over where you want to append data, while `.innerHTML does not.

The final benefit of .insertAdjacentHTML is it does not corrupt the DOM. Here is how .innerHTML += works.

  1. It gets the value of .innerHTML by serializing the descendants of element.
  2. It appends the right hand side of += to the string.
  3. It removes the children of element.
  4. It parses the new string that contains the serialization of the old descendants followed by some new markup. This reserialization also results in losing all handlers you have attached to the element. Obviously, the last benefit does not really apply in the case of using .innerHTML =.

Other alternatives to .innerHTML are the .insertBefore method, which as its name suggests inserts a node as a child before another node, as well as the .appendChild method which inserts a child node as the last node.

.insertAdjacentHTML is something of a multi-functional tool seeing as it can perform the jobs of .innerHTML, .insertBefore, as well as .appendChild.

Sources: https://hacks.mozilla.org/2011/11/insertadjacenthtml-enables-faster-html-snippet-injection/

like image 110
Azrael Avatar answered Jun 27 '26 23:06

Azrael



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!