How to convert an HTML Element to a string with JavaScript?

Spread the love

Sometimes, we want to convert an HTML Element to a string with JavaScript.

In this article, wwe’ll look at how to convert an HTML Element to a string with JavaScript.

How to convert an HTML Element to a string with JavaScript?

To convert an HTML Element to a string with JavaScript, we use the outerHTML property.

For instance, we write

<div id="new-element-1">Hello world.</div>

to add a div.

Then we write

const element = document.getElementById("new-element-1");
const elementHtml = element.outerHTML;

to select the element with getElementById.

Then we convert it to a string by getting the outerHTML property.

Conclusion

To convert an HTML Element to a string with JavaScript, we use the outerHTML property.

Leave a Reply

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