-2

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?

I'm happy doing the escaping, I've just no idea how to return the HTML from an object.

If there's a simple DOM-standard way of doing this too, I'm just as happy with that.


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:

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

4

4 回答 4

16

如果你有身份证,那么你可以这样做......

jQuery

$("#ID")[0].outerHTML;

纯Javascript

document.getElementById("ID").outerHTML;

使用.html()只会获取内部 html,而不包含您通过 ID 指定的元素。

更新

现在还有一个 jQuery 方法来获取元素的外部 HTML...

$("#ID").outerHTML();
于 2013-11-05T11:59:24.570 回答
2

是的,jquery 的 html() 方法以字符串形式返回所有标签的 html 数据: 示例:

html源

<div id="DivId">
    <p> This is html concept </p>
    <br/>
    <p> This is jquery concept. </p>
</div>

jQuery代码

var htmlString=$("#DivId").html();

返回结果是: htmlString:

    <p> This is html concept </p>
    <br/>
    <p> This is jquery concept. </p>
于 2013-11-05T12:07:20.977 回答
0

给定一个 Jquery 选择器,我可以得到一个项目(及其子项)的原始 HTML

使用方法获取值.html()

var htmlOutput = $('#myselector').html();

...这样我就可以,例如,将该 HTML 的转义版本放回页面上?

使用.text()方法将字符串设置为纯文本:

$('#anotherselector').text(htmlOutput);

(即 jQuery 将为您完全转义它;您无需手动执行)

于 2013-11-05T12:01:41.080 回答
0

是的,它可能的用途html()

var source=$('#ID').html()
于 2013-11-05T11:59:16.363 回答