Create string from HTMLDivElement

前端 未结 6 1682
醉酒成梦
醉酒成梦 2020-12-29 06:27

What I would like to be able to do is create a string from a Javascript HTMLElement Object. For example:

var day = document.createElement(\"div\");
day.class         


        
6条回答
  •  灰色年华
    2020-12-29 06:55

    Variant on Gump's wrapper, since his implementation lifts the target node out of the document.

    function nodeToString ( node ) {
       var tmpNode = document.createElement( "div" );
       tmpNode.appendChild( node.cloneNode( true ) );
       var str = tmpNode.innerHTML;
       tmpNode = node = null; // prevent memory leaks in IE
       return str;
    }
    

    To print the resulting string on screen (re: escaped)

    var escapedStr = nodeToString( node ).replace( "<" , "<" ).replace( ">" , ">");
    outputNode.innerHTML += escapedStr;
    

    Note, attributes like "class" , "id" , etc being stringified properly is questionable.

提交回复
热议问题