Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

<span>...</span> 

Any ideas? Thanks

like image 743
Richard H Avatar asked Nov 19 '09 14:11

Richard H


2 Answers

Use outerHTML:

var el = document.getElementById( 'foo' ); alert( el.outerHTML ); 
like image 187
Majkel Avatar answered Sep 19 '22 20:09

Majkel


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

var target = document.getElementById('myElement'); var wrap = document.createElement('div'); wrap.appendChild(target.cloneNode(true)); alert(wrap.innerHTML); 

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.

like image 25
Jørn Schou-Rode Avatar answered Sep 19 '22 20:09

Jørn Schou-Rode