Search code examples
javascripthtml

How to convert a HTMLElement to a string


I am going to create an XML element in JavaScript to exchange data with server side. I found I can do it with document.createElement. But I do not know how to convert it to string. Is there any API in browser to make it easier? Or is there any JS library including this API?

EDIT: I found that browser API XMLSerializer, it should be the right way to serialize to string.


Solution

  • 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;
    }