How to convert a HTMLElement to a string
The element outerHTML
property (note: supported by Firefox after version 11) returns the HTML of the entire element.
Example
<div id="new-element-1">Hello world.</div>
<script type="text/javascript"><!--
var element = document.getElementById("new-element-1");
var elementHtml = element.outerHTML;
// <div id="new-element-1">Hello world.</div>
--></script>
Similarly, you can use innerHTML
to get the HTML contained within a given element, or innerText
to get the text inside an element (sans HTML markup).
See Also
- outerHTML - Javascript Property
- Javascript Reference - Elements
You can get the 'outer-html' by cloning the element, adding it to an empty,'offstage' container, and reading the container's innerHTML.
This example takes an optional second parameter.
Call document.getHTML(element, true) to include the element's descendents.
document.getHTML= function(who, deep){
if(!who || !who.tagName) return '';
var txt, ax, el= document.createElement("div");
el.appendChild(who.cloneNode(false));
txt= el.innerHTML;
if(deep){
ax= txt.indexOf('>')+1;
txt= txt.substring(0, ax)+who.innerHTML+ txt.substring(ax);
}
el= null;
return txt;
}