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 moviesvar clone = document.getElementById('myElement').cloneNode(true);
var html = clone.outerHTML;
Using CSS selectors
// For when you feel classy or need to match specific attributesvar html = document.querySelector('.myClass[attr="value"]').outerHTML;
Handling old school browsers
// When you need to go old school with a wrapper divvar 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 elementsvar html = new XMLSerializer().serializeToString(document.getElementById('complexTable'));
Advanced targeting with createRange()
// Like a sniper, choosing your targets with precisionvar 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.