How to Convert an HTMLElement to a String
To transform an HTMLElement
into a string, you can use the property, outerHTML
:
This line of code assigns the element's HTML markup to elementString
.
More fine-grained solutions
Need to serialize an element without including its descendant elements? Or perhaps you're after the text content only? Here's how to do it:
innerHTML
and innerText
in action
When you desire the HTML content inside an element, innerHTML
comes to the rescue:
Or, choose innerText
to receive plain text sans any HTML rushing in:
Introducing the XMLSerializer
For a thorough, all-inclusive, and more browser-friendly approach, go for the XMLSerializer
:
This doesn't discriminate against elements with incomplete browser support, and gives you the whole group photo, not just a select few.
The challenge with namespaces and XML
When you're faced with XML namespaces or you need to serialize an HTMLElement
that has inline SVG or MathML, don't give up:
This works wonders for elements within XML documents, recreating them more accurately than outerHTML
A note on element attributes
To include element attributes in your serialization, you could:
Combine this with the element's tag name and innerHTML for a full-bodied string representation.
Leverage the JavaScript ecosystem
In the ocean of JavaScript libraries and frameworks, there may be utility functions ready and waiting. Check the documentation pages of React, Angular, Vue, etc., for built-in solutions.
Don't forget the security
Be mindful of the risk of cross-site scripting (XSS) - it's definitely not a party you want to throw. Sanitize output, especially if it originates from user input or is going to be rendered in an HTML context.
Need the whole shebang? Doctype and document fragments
In some cases, you might need to serialize a full document fragment or include the doctype declaration:
This captures a complete snapshot of your document with all the trimmings.
Was this article helpful?