How to use insertAdjacentHTML

insertAdjacentHTMLThis is a very cool DOM method, we can call any DOM element to add new content to the page.

This is a nice and flexible way to insert new content.

This method is called on an element and accepts 2 parameters: position and a string containing HTML.

This is an example:

const item = `<div>
    test
  </div>
`

document.querySelector(’#container’).insertAdjacentHTML(‘afterend’, item)

noteafterendString.

This represents where we add the HTML to the container.

We have 4 possible positions:

  • beforebeginBefore the element
  • afterbeginBefore the first child element of the element
  • beforeendAfter the last child element of the element
  • afterendAfter the element

This is how we add new items to the list:

document.querySelector('ul').insertAdjacentHTML('beforeend', '<li>item</li>')

Download mine for freeJavaScript beginner's manual


More browser tutorials: