Explain Codes LogoExplain Codes Logo

How to Convert an HTMLElement to a String

javascript
serialization
xmlserializer
xss-prevention
Nikita BarsukovbyNikita Barsukov·Aug 22, 2024
TLDR

To transform an HTMLElement into a string, you can use the property, outerHTML:

const elementString = document.getElementById('yourElementId').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:

// Shallow serialization – includes the element, but not its children. // Or as I like to call it, "playing favorites". const shallowString = document.getElementById('yourElementId').cloneNode().outerHTML; // When you just want the gossip, not the whole story. const textString = document.getElementById('yourElementId').innerText;

innerHTML and innerText in action

When you desire the HTML content inside an element, innerHTML comes to the rescue:

const innerHTMLContent = document.getElementById('yourElementId').innerHTML;

Or, choose innerText to receive plain text sans any HTML rushing in:

const plainTextContent = document.getElementById('yourElementId').innerText;

Introducing the XMLSerializer

For a thorough, all-inclusive, and more browser-friendly approach, go for the XMLSerializer:

const serializer = new XMLSerializer(); const serializedElement = serializer.serializeToString(document.getElementById('yourElementId'));

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:

const element = document.getElementById('yourElementId'); const serializedXML = new XMLSerializer().serializeToString(element);

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:

const element = document.getElementById('yourElementId'); let attributesString = ""; for (let attribute of element.attributes) { // Everyone gets their 15 minutes of fame attributesString += ` ${attribute.name}="${attribute.value}"`; }

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:

const doctype = new XMLSerializer().serializeToString(document.doctype); const theWholeKitAndCaboodle = doctype + document.documentElement.outerHTML;

This captures a complete snapshot of your document with all the trimmings.