Convert DOM to String

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);

8 comments

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

  2. @John
    Thnks for the info :)

  3. For XML, you can just do:

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

  4. @Timo cool, thanks for the info.

  5. lol …people neglect to mention a few critical things …that are driving me crazy

    1. XMLSerializer works beautifully BUT NOT IN IE
    2. inner/outerHTML are junk – for one thing they strip out the trailing slash in singleton nodes ie. becomes rendering valid XHTML invalid in the conversion (I believe there are other problems also

  6. sorry this site doesn’t handle special character input I see so let me try again … <br/> becomes <br> when using inner/outerHTML

    …I’m so completely sick of poorly designed software that is release on the unsuspecting developer

  7. <br /> isn’t right anyways. So it becoming <br> is the right thing to happen. Am I right on this or is that wrong?

  8. If you see the spec the end tag in BR is “forbidden” http://www.w3.org/TR/html401/struct/text.html#edef-BR

    I think this is one of the common mistakes people do while writing BR tags and since most of us don’t validate our html these things go unnoticed.

Leave a comment