📜 ⬆️ ⬇️

JavaScript method insertAdjacentHTML and beforeend

Translation of the article "JavaScript insertAdjacentHTML and beforeend", David Walsh.

If you didn't know: bloody DOM is very slow. And as our sites become more dynamic and AJAX-using, it becomes more and more important for us to manage the DOM tree with the least performance damage. I recently wrote an article about DocumentFragments. This is a reasonable approach to merging the list of child elements under a certain “pseudo-element”, for further placement into a real DOM element. Another great method for working with insertAdjacentHTML elements is the way to add elements to the parent element without affecting its other descendants.

Javascript


For example, you get a piece of HTML code as a string, received via an AJAX request, usually in this case we put this code in the parent element through the innerHTML property:

 function onSuccess(newHtml) { parentNode.innerHTML += newHtml; } 

The problem with this code is that any links or events attached to the child elements are destroyed after the innerHTML parent element is modified, even if you simply add markup to the end of the parent element - the insertAdjacentHTML method solves this problem:
')
 function onSuccess(newHtml) { parentList.insertAdjacentHTML('beforeend', newHtml); } 

This code adds code to the end of the parent element without affecting its other descendants. This is an ingenious way to add a markup element without creating an intermediate parent element for the added code.

This is how we learned about the existence of the problem and how to avoid it with the help of the described insertAdjacentHTML . Do not forget this method, as it is not so famous, but nevertheless very useful.

Source: https://habr.com/ru/post/235333/


All Articles