javascript 我可以使用 Jquery 获取元素的 HTML 源代码吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19788402/
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
Can I get the HTML source of an element with Jquery?
提问by Oli
Rather an odd request, I'm sure, but given a Jquery selector, can I get the raw HTML of an item (and its children) so that I could, for example, put an escaped version of that HTML back on the page?
我敢肯定,这是一个奇怪的请求,但是给定一个 Jquery 选择器,我能否获取项目(及其子项)的原始 HTML,以便我可以,例如,将该 HTML 的转义版本放回页面上?
I'm happy doing the escaping, I've just no idea how to return the HTML from an object.
我很高兴进行转义,我只是不知道如何从对象返回 HTML。
If there's a simple DOM-standard way of doing this too, I'm just as happy with that.
如果也有一种简单的 DOM 标准方法可以做到这一点,我也很高兴。
Edit to addresss the "Oh why didn't you just Google that": Google it. You'll get Jquery's .html()
and that will give you the inner HTML of an object. For example, let'sa say you have:
编辑以解决“哦,为什么你不只是谷歌那个”:谷歌它。你会得到 Jquery 的.html()
,它会给你一个对象的内部 HTML。例如,假设您有:
<div id="pants">naughty bits</div>
.html()
will only return naughty bits
. while the output I'm looking for is <div id="pants">naughty bits</div>
.html()
只会返回naughty bits
。而我正在寻找的输出是<div id="pants">naughty bits</div>
回答by Reinstate Monica Cellio
If you have the ID then you can do it like this...
如果你有ID,那么你可以这样做......
jQuery
jQuery
$("#ID")[0].outerHTML;
Pure Javascript
纯Javascript
document.getElementById("ID").outerHTML;
Using .html()
will only get the inner html and not include the element you specify by ID.
使用.html()
只会获取内部 html,而不包含您通过 ID 指定的元素。
Update
更新
There is now also a jQuery method to get the outer HTML of an element...
现在还有一个 jQuery 方法来获取元素的外部 HTML...
$("#ID").outerHTML();
回答by Ramakant Shukla
Yes, html() method of jquery return html data with all tags as an string: Example:
是的,jquery 的 html() 方法将所有标签作为字符串返回 html 数据:示例:
Html Source
html源
<div id="DivId">
<p> This is html concept </p>
<br/>
<p> This is jquery concept. </p>
</div>
Jquery Code
查询代码
var htmlString=$("#DivId").html();
Return Result is:htmlString:
返回结果为:htmlString:
<p> This is html concept </p>
<br/>
<p> This is jquery concept. </p>
回答by Spudley
given a Jquery selector, can I get the raw HTML of an item (and its children)
给定一个 Jquery 选择器,我可以获取项目(及其子项)的原始 HTML
Get the value using the .html()
method:
使用以下.html()
方法获取值:
var htmlOutput = $('#myselector').html();
...so that I could, for example, put an escaped version of that HTML back on the page?
...这样我就可以,例如,将该 HTML 的转义版本放回页面上?
Use the.text()
method to set the string as plain text:
使用.text()
方法将字符串设置为纯文本:
$('#anotherselector').text(htmlOutput);
(ie jQuery will fully escape it for you; you don't need to do it manually)
(即 jQuery 会为您完全转义它;您不需要手动执行此操作)
回答by Sridhar R
Yes its possible use html()
是的,它可能的用途 html()
var source=$('#ID').html()