How to insert HTML elements with JavaScript?

Spread the love

Sometimes, we want to insert HTML elements with JavaScript.

In this article, we’ll look at how to insert HTML elements with JavaScript.

How to insert HTML elements with JavaScript?

To insert HTML elements with JavaScript, we use 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 element.insertAdjacentHTML with 'afterend' and newElement to add newElement after the element as its sibling.

Conclusion

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

Leave a Reply

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