从 jQuery 集合中删除注释和文本节点

Removing comments and text nodes from jQuery collection

本文关键字:文本 节点 注释 删除 jQuery 集合      更新时间:2023-09-26
$html = $("<!-- comment --> <p>text</p>");

创建一个像这样的jQuery集合

$( [the comment], [text node], p )

如何仅访问该段落? .find("p"( 返回一个空集合

而且,对于加分,

$html = $("<p>text</p>");

创建一个像这样的jQuery集合

$( p )

有没有一种故障安全的方法可以获取 p,并且只有 p,无论评论是否存在都有效?

最简单的方法是使用 filter 和通用选择器 * ,它匹配所有元素

$html = $("<!-- comment --> <p>text</p>").filter('*');
var p = $html.filter(function() { return this.nodeType === 1; });

jsFiddle。

试试这个演示。也许这不是你要使用它的方式,但你明白了。

<div class="text">
    <!-- comment -->
    <p>text</p>
</div>
var html = $('.text').html();
html = $.trim(html.replace(/<!--(.*?)-->/ig, ''));
alert(html);

一种方法是像$html = $("<!-- comment --> <p>text</p>");一样按索引获取,您可以使用$($html[2])获取p标签。

$html = $("<!-- comment --> <p>text</p>");
$target = new Object();
for(key in $html){
    if(typeof $html[key] ===  'object' && $html[key].localName === 'p')
        $target = $html[key];
}