Explain Codes LogoExplain Codes Logo

How to get the HTML for a DOM element in JavaScript

javascript
prompt-engineering
functions
callbacks
Nikita BarsukovbyNikita Barsukov·Dec 31, 2024
TLDR

Instantly extract an element's full HTML with element.outerHTML:

var html = document.getElementById('myElement').outerHTML;

For the inner content only, use element.innerHTML.

Alternative solutions

Beyond outerHTML, here are other options tailored for different scenarios:

Make a clone for safety

// Clones are a lot safer, and not just in Sci-Fi movies var clone = document.getElementById('myElement').cloneNode(true); var html = clone.outerHTML;

Using CSS selectors

// For when you feel classy or need to match specific attributes var html = document.querySelector('.myClass[attr="value"]').outerHTML;

Handling old school browsers

// When you need to go old school with a wrapper div var el = document.getElementById('myElement'); var wrapper = document.createElement('div'); wrapper.appendChild(el.cloneNode(true)); var html = wrapper.innerHTML;

By understanding outerHTML against innerHTML, you're loading your JS arsenal with more firepower.

Deep dive

Working with complex structures

// For when things get complicated, like Inception-level nested elements var html = new XMLSerializer().serializeToString(document.getElementById('complexTable'));

Advanced targeting with createRange()

// Like a sniper, choosing your targets with precision var range = document.createRange(); range.selectNode(document.getElementById('partialContent')); var html = range.cloneContents().outerHTML;

Minimise browser reflow

// Be efficient! We're not mining Bitcoin here. // Clone and work with off-DOM nodes. // Delay DOM operations until you have a batch ready.