Javascript 从jQuery集合中删除注释和文本节点
我怎样才能只看这一段。find(“p”)返回一个空集合 另外,为了获得额外的分数Javascript 从jQuery集合中删除注释和文本节点,javascript,jquery,comments,textnode,Javascript,Jquery,Comments,Textnode,我怎样才能只看这一段。find(“p”)返回一个空集合 另外,为了获得额外的分数 $( [the comment], [text node], p ) 是否有一种故障安全的方法来获取p,并且无论注释是否存在,只有p才有效 $( p ) .最简单的方法是使用过滤器和通用选择器*,它匹配所有元素 $html=$(“text”)。过滤器('*'); 试试这个。也许你不打算这么做,但你明白了 $html = $("<!-- comment --> <p>text</p&
$( [the comment], [text node], p )
是否有一种故障安全的方法来获取p,并且无论注释是否存在,只有p才有效
$( p )
.最简单的方法是使用
过滤器和通用选择器*
,它匹配所有元素
$html=$(“text”)。过滤器('*');
试试这个。也许你不打算这么做,但你明白了
$html = $("<!-- comment --> <p>text</p>").filter('*');
正文
var html=$('.text').html();
html=$.trim(html.replace(//ig',);
警报(html);
一种方法是通过索引获取,如$html=$(“text”)中所示
您可以使用$($html[2])
获取p标记
或
$html=$(“text”);
$target=新对象();
for(输入$html){
if(typeof$html[key]==='object'&&&html[key].localName=='p')
$target=$html[key];
}
返回一个空选择。contents()
调用是不必要的。严格来说,它解决了问题,但我认为这有点忽略了重点。是的filter
在集合上工作,而find
确实需要一个“根”DOM节点作为起点。要仅获取p
内容,$(“text”)。filter('p')代码>@Jean Charles嗯,是的。我以问题的标题为准,以问题的正文为例。最好使用“nodeName”而不是“localName”。
$( p )
var p = $html.filter(function() { return this.nodeType === 1; });
$html = $("<!-- comment --> <p>text</p>").filter('*');
<div class="text">
<!-- comment -->
<p>text</p>
</div>
var html = $('.text').html();
html = $.trim(html.replace(/<!--(.*?)-->/ig, ''));
alert(html);
$html = $("<!-- comment --> <p>text</p>");
$target = new Object();
for(key in $html){
if(typeof $html[key] === 'object' && $html[key].localName === 'p')
$target = $html[key];
}