Get the string representation of a DOM node

前端 未结 11 2129
傲寒
傲寒 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:34

    Use Element#outerHTML:

    var el = document.createElement("p");
    el.appendChild(document.createTextNode("Test"));
    
    console.log(el.outerHTML);
    

    It can also be used to write DOM elements. From Mozilla's documentation:

    The outerHTML attribute of the element DOM interface gets the serialized HTML fragment describing the element including its descendants. It can be set to replace the element with nodes parsed from the given string.

    https://developer.mozilla.org/en-US/docs/Web/API/Element/outerHTML

提交回复
热议问题