tags:

views:

279

answers:

4

Hi, is there a way to convert a javascript HTML object to a string? i.e.

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

thanks a lot in advance

+1  A: 
someElement.innerHTML
Darin Dimitrov
but in that case i will get the contents of the <div> tag and not the tag itself, i.e. if i have <div id="id" style="......"> </div>then by using .innerHTML i get " " and not '<div id="id" style="......."> </div>'
Lina
Then use `outerHTML`.
Darin Dimitrov
+5  A: 

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); 
Andy E
A: 

As Darin Dimitrov said you can use element.innerHTML to display the HTML element childnodes HTML. If you are under IE you can use the outerHTML propoerty that is the element plus its descendants nodes HTML

Gregoire
+1  A: 

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;
}
kennebec
that's great, and very helpful thanks :)
Lina