Richard H Richard H - 2 years ago 143
HTML Question

How to get the HTML for a DOM element in javascript

Imagine I have the following HTML:

<div><span><b>This is in bold</b></span></div>

I want to get the HTML for the div, including the div itself. Element.innerHTML only returns:


Any ideas? Thanks

Answer Source

Expanding on jldupont's answer, you could create a wrapping element on the fly:

var target = document.getElementById('myElement');
var wrap = document.createElement('div');

I am cloning the element to avoid having to remove and reinsert the element in the actual document. This might be expensive if the element you wish to print has a very large tree below it, though.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download