Categories
JavaScript Answers

How to append HTML string to the DOM with JavaScript?

Spread the love

To append HTML string to the DOM with JavaScript, we create an element with the HTML inside.

For instance, we write

const child = document.createElement("div");
child.innerHTML = str;
child = child.firstChild;
document.getElementById("test").appendChild(child);

to create the div with createElement.

And then we set its innerHTML property to the HTML string str.

Next, we get the first chilld of the div with firstChild.

And then we call appendChild to append the child as the last child o the element with ID test.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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