Skip to main content

innerHTML Property

Another way to create DOM elements and put them in a tree is to use strings with tags and let the browser do all the hard work. This approach has its pros and cons.

Reading

The innerHTML property stores the content of an element, including tags, as a string. The return value is always valid HTML code.

Changing

The innerHTML property is both readable and writable. If you write a string with HTML tags to it, then the browser, while parsing the string, will turn them into valid elements and add them to the DOM tree.

Note

If you write an empty string to the innerHTML property, the content of the element will be cleared. This is an easy and quick way to delete all content.

With this approach, unlike document.createElement(), you do not get a reference to the created DOM element. This is the first step towards templating, i.e. creating a large amount of similar markup with different data according to a preset template. For example, as in the list of products of an online store, etc.

Uniform (template) markup is created from a data array. The trick is to iterate over this array and create a single string with HTML tags, which is then written to the element's innerHTML.

Addition

Modifying elem.innerHTML will completely remove and re-create all descendants of the elem element. If the element is not empty from the beginning, then you will incur additional costs for serializing the existing markup, which is bad.

Note

Use the elem.innerHTML property for adding only when the elem element is empty or if you want to completely replace its content.

insertAdjacentHTML() method

This is a present-day method for adding a string with HTML tags before, after or inside an element. It solves the problem of innerHTML with re-serializing the content of an element when adding markup to the existing one.

elem.insertAdjacentHTML(position, string);

The position argument is a string, position relative to the elem element. It takes one of the four values below:

inserAdjacentHTML method
  • "beforebegin" - before elem
  • "afterbegin" - inside elem, before all children
  • "beforeend" - inside elem, after all children
  • "afterend" - after elem
Note

"beforebegin" and "afterend" only work if elem is already in the DOM tree.