Sometimes, we want to convert a JavaScript string to an HTML element.
In this article, we’ll look at how to convert a JavaScript string to an HTML element.
How to convert a JavaScript string to an HTML element?
To convert a JavaScript string to an HTML element, we set the innerHTML
property.
For instance, we write
const s = '<div id="myDiv"></div>';
const htmlObject = document.createElement("div");
htmlObject.innerHTML = s;
to create a div with createElement
.
Then we set its innerHTML
property to the s
string to render the HTML in the string in the div.
Conclusion
To convert a JavaScript string to an HTML element, we set the innerHTML
property.