Easy tech stuff!

Convert DOM to String

Posted: February 15th, 2008 | Author: Nischal Shetty | Filed under: JavaScript | 4 Comments »

While working on one of my projects I came across a scenario where I needed to convert the DOM object into a String representation to send it as an AJAX request parameter.

The way to do this is as follows:

Suppose you have a form named “Test”.

We first get the DOM object of the current page as follows:

var domObject = document.Test;

//Now lets convert this DOM to String

var domToString = domObject.innerHTML;

Thats it!!! Put an alert and you’ll see the complete DOM in a string representation.

alert(domToString);

http://www.techtamasha.com/wp-content/plugins/sociofluid/images/digg_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/reddit_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/delicious_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/furl_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/technorati_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/google_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/myspace_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/facebook_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/yahoobuzz_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/twitter_48.png

4 Comments on “Convert DOM to String”

  1. 1 John Stracke said at 12:58 pm on March 16th, 2010:

    Minor point: this apparently doesn’t work for XML documents.

  2. 2 Nischal Shetty said at 2:55 am on March 17th, 2010:

    @John
    Thnks for the info :)

  3. 3 Timo said at 9:14 am on July 23rd, 2010:

    For XML, you can just do:

    var str = (new XMLSerializer()).serializeToString(domObject);

  4. 4 Nischal Shetty said at 11:59 am on July 24th, 2010:

    @Timo cool, thanks for the info.


Leave a Reply