javascript getElementById and convert it to String

If you want a string representation of the entire tag then you can use outerHTML for browsers that support it:

var someElementToString = someElement.outerHTML;

For other browsers, apparently you can use XMLSerializer:

var someElement = document.getElementById("id");
var someElementToString;

if (someElement.outerHTML)
    someElementToString = someElement.outerHTML;
else if (XMLSerializer)
    someElementToString = new XMLSerializer().serializeToString(someElement); 

You can always wrap a clone of an element in an 'offscreen', empty container. The container's innerHTML is the 'outerHTML' of the clone- and the original. Pass true as a second parameter to get the element's descendents as well.

document.getHTML=function(who,deep){ 
 if(!who || !who.tagName) return '';
 var txt, el= document.createElement("div");
 el.appendChild(who.cloneNode(deep));
 txt= el.innerHTML;
 el= null;
 return txt;
}

Tags:

Javascript