Sometimes, we want to get the string representation of a DOM node with JavaScript.
In this article, we’ll look at how to get the string representation of a DOM node with JavaScript.
How to get the string representation of a DOM node with JavaScript?
To get the string representation of a DOM node with JavaScript, we can use the outerHTML property.
For instance, we write
const el = document.createElement("p");
el.appendChild(document.createTextNode("Test"));
const tmp = document.createElement("div");
tmp.appendChild(el);
console.log(tmp.outerHTML);
to create the p element with createElement.
And then we call appendChild to append a text node as its last child to it that we created with createTextNode.
Then we create the tmp element with `createElement.
And then we call tmp.appendChild to append the p element el as the last child of it.
Finally, we get the HTML string version of tmp with tmp.outerHTML.
Conclusion
To get the string representation of a DOM node with JavaScript, we can use the outerHTML property.