Get the string representation of a DOM node

前端 未结 11 2120
傲寒
傲寒 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

    You can create a temporary parent node, and get the innerHTML content of it:

    var el = document.createElement("p");
    el.appendChild(document.createTextNode("Test"));
    
    var tmp = document.createElement("div");
    tmp.appendChild(el);
    console.log(tmp.innerHTML); // 

    Test

    EDIT: Please see answer below about outerHTML. el.outerHTML should be all that is needed.

提交回复
热议问题