Get the string representation of a DOM node

前端 未结 11 2144
傲寒
傲寒 2020-12-01 03:56

Javascript: I have the DOM representation of a node (element or document) and I\'m looking for the string representation of it. E.g.,

var el = document.creat         


        
11条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-01 04:40

    What you're looking for is 'outerHTML', but wee need a fallback coz it's not compatible with old browsers.

    var getString = (function() {
      var DIV = document.createElement("div");
    
      if ('outerHTML' in DIV)
        return function(node) {
          return node.outerHTML;
        };
    
      return function(node) {
        var div = DIV.cloneNode();
        div.appendChild(node.cloneNode(true));
        return div.innerHTML;
      };
    
    })();
    
    // getString(el) == "

    Test

    "

    You'll find my jQuery plugin here: Get selected element's outer HTML

提交回复
热议问题