javascript 获取 jQuery 和/或 DOM 对象的 HTML 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16466776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 04:47:45  来源:igfitidea点击:

Get HTML String for jQuery and/or DOM object

javascriptjquerydom

提问by Joachim Kurz

I think I've read through the complete jQuery API documentationand 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 API 文档,并在调试器中查看了 jQuery 对象和简单的 DOM 元素,以检查它们在运行时实际拥有的方法,但是对于我的一生,我找不到方法来获取表示 jQuery 对象或 DOM 节点内容的 html 字符串。我错过了什么吗?

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

jQuery 对象有方法html(),DOM 元素有属性,innerHTML但两者都只给出对象的内部 html。所以如果我有这样的 HTML:

<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).

我使用 jQuery 做这样的事情var $div = $body.find("div"),然后我调用$div.html()返回的字符串 is "<p>Hello World!</p>"。但我正在寻找一种方法让它返回"<div><p>Hello World!</p></div>"(我不关心空格)。

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

我究竟做错了什么?获取这些对象的 html 表示不会那么困难,是吗?

回答by Colleen

try the dom property .outerHTML

试试 dom 属性 .outerHTML

回答by Nate

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

您可以使用“.outerHTML”属性。这是使用 jquery 的样子:http: //jsfiddle.net/MHvmm/

$('div')[0].outerHTML

回答by Jan

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?

这可以通过将您想要的对象包含在另一个对象中并获取 innerHTML 来实现。这里有更详细的解释: 如何将 jQuery 对象转换为字符串?