Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
insertAdjacentHTML is a DOM method you can call on any element to add new content to a page.
It is a nice and flexible way to insert new content.
The method is called on an element and accepts 2 parameters: the position, and a string containing HTML.
Here’s an example:
const item = `<div>
test
</div>
`
document.querySelector('#container').insertAdjacentHTML('afterend', item)
Notice the afterend string.
This is the position where the HTML is inserted relative to the container.
We have 4 possible positions:
beforebeginbefore the elementafterbeginbefore the first child of the elementbeforeendafter the last child of the elementafterendafter the element
Here’s how we would add a new item to a list:
document.querySelector('ul').insertAdjacentHTML('beforeend', '<li>item</li>')