Get HTML String for jQuery and/or DOM object

与世无争的帅哥 提交于 2020-01-21 07:38:25

问题


I think I've read through the complete jQuery API documentation and looked at jQuery objects and simple DOM elements in the debugger to check what methods they actually have at runtime, but for the life of me, I can't find a way to get the html string that represents the contents of a jQuery object or a DOM Node. Am I missing something?

jQuery objects have the method html(), DOM elements have the property innerHTML but both only give the inner html of the object. So if I have HTML like this:

<body>
    <div>
        <p>Hello World!</p>
    </div>
</body>

And I use jQuery doing something like this var $div = $body.find("div") and I then call $div.html() the returned string is "<p>Hello World!</p>". But I'm looking for a way to make it return "<div><p>Hello World!</p></div>" (I don't care about the whitespace).

What am I doing wrong? It can't be that difficult to get the html representation of these objects, can it?


回答1:


try the dom property .outerHTML




回答2:


You can use the '.outerHTML' property. This is how it would look using jquery: http://jsfiddle.net/MHvmm/

$('div')[0].outerHTML



回答3:


This is possible by enclosing your desired object in another object, and the fetching the innerHTML. It is explained in much more detail here: How do you convert a jQuery object into a string?



来源:https://stackoverflow.com/questions/16466776/get-html-string-for-jquery-and-or-dom-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!