How to insert HTML elements with JavaScript?

Spread the love

To insert HTML elements with JavaScript, we call the insertAdjancentHTML method.

For instance, we write

const element = document.getElementById("one");
const newElement = '<div id="two">two</div>';
element.insertAdjacentHTML("afterend", newElement);

to call getElementById to get the element.

Then we call insertAdjacentHTML to insert the element in the newElement string as the element after element with 'afterend'.

Leave a Reply

Your email address will not be published. Required fields are marked *