JavaScript insertAdjacentHTML and beforeend method

Original author: David Walsh
  • Transfer
Translation of the article "JavaScript insertAdjacentHTML and beforeend", David Walsh.

If you didn’t know: the damn 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 damage to performance. I recently wrote an article about DocumentFragments. This is a reasonable approach to combining the list of children under a certain “pseudo-element”, for further placement in a real DOM element. Another great method for working with elements insertAdjacentHTML: this is the way to add elements to the parent element without affecting its other descendants.


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

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

The problem in this code is that any links or events attached to the child elements will be destroyed after the innerHTMLparent element is changed , even if you just add markup at 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 markup to an element without creating an intermediate parent element for the added code.

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

Also popular now: