Create string from HTMLDivElement

前端 未结 6 1643
醉酒成梦
醉酒成梦 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:52

    You can wrap that element into another element and use innerHTML on it:

    var wrapper = document.createElement("div");
    wrapper.appendChild(day);
    var str = wrapper.innerHTML;
    
    0 讨论(0)
  • 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( "<" , "&lt;" ).replace( ">" , "&gt;");
    outputNode.innerHTML += escapedStr;
    

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

    0 讨论(0)
  • 2020-12-29 06:56

    Why would you use createElement if you can also directly parse a string? Like: var string = '<div class="' + class + '">' + text + '</div>';

    0 讨论(0)
  • 2020-12-29 06:57

    You can use this function (taken from pure.js)

    function outerHTML(node){
     return node.outerHTML || new XMLSerializer().serializeToString(node);
    }
    
    0 讨论(0)
  • 2020-12-29 07:09

    You need to create text node to add text for your created element like this:

    var day = document.createElement("div");
    day.className = "day";
    // create text node
    var txt = document.createTextNode('Random Text');
    // add text to div now
    day.appendChild(txt);
    // append to body
    document.body.appendChild(day);
    
    0 讨论(0)
  • 2020-12-29 07:18

    Since a few years have passed since the last answers I found that .outerHTML seems now to be supported by all major browsers (see: https://caniuse.com/#search=outerhtml). So in order to get the HTML of an JS element you can do the following:

    var day = document.createElement("div");
    day.className = "day";
    day.textContent = "Random Text";
    
    console.log(day.outerHTML)
    

    Which gives you: <div class="day">Random Text</div>

    0 讨论(0)
提交回复
热议问题