How to convert an HTML string into DOM elements with JavaScript?

Spread the love

Sometimes, we want to convert an HTML string into DOM elements with JavaScript.

In trhis article, we’ll look at how to convert an HTML string into DOM elements with JavaScript.

How to convert an HTML string into DOM elements with JavaScript?

To convert an HTML string into DOM elements with JavaScript, we can create a new element.

For instance, we write

const wrapper = document.createElement("div");
wrapper.innerHTML = '<div><a href="#"></a><span></span></div>';
const div = wrapper.firstChild;

to create a div with createElement.

Then we set its innerHTML property to the HTML code we want to convert.

And then we get the first child node in the div with firstChild.

Conclusion

To convert an HTML string into DOM elements with JavaScript, we can create a new element.

Leave a Reply

Your email address will not be published.