在jQuery中选择元素时忽略子元素 [英] Ignore child elements when selecting elements in jQuery
问题描述
这是我的HTML:
<div class="foo">
<span class="ignore_this">IGNORE THIS TEXT</span>
SELECT THIS
</div>
我正在尝试找出如何选择foo
中的所有内容,而不是选择ignore_this
中的所有内容:
I'm trying to figure out how to select all the stuff inside foo
, but not the stuff inside ignore_this
:
$("div.foo:not(span.ignore_this)").text()
但是我不知道怎么做.
推荐答案
选择器div.foo:not(span.ignore_this)
说匹配每个不是span.ignore_this
的div.foo
",这只会选择一个元素:
The selector div.foo:not(span.ignore_this)
is saying "match every div.foo
that isn't a span.ignore_this
" which is only going to select one element: div.foo
. If you restructured your html like this:
<div class="foo">
<span class="ignore_this">IGNORE THIS TEXT</span>
<span>SELECT THIS</span>
</div>
然后您可以致电:
$('div.foo span:not(.ignore_this)').text();
与div.foo
的后代(不是.ignore_this
)的所有span
元素匹配.
Which matches all span
elements which are descendants of a div.foo
that are not .ignore_this
.
如果您不具备重新格式化html格式的能力,那么您可以通过额外的处理器周期来完成所需的工作:
If you don't have the luxury of reformatting the html, then you could accomplish what you want with extra processor cycles:
var clone = $('div.foo').clone();
$('span.ignore_this', clone).remove();
var text = clone.text();
这篇关于在jQuery中选择元素时忽略子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!