选择不是指定元素后代的所有元素 [英] Select all elements that are not a descendant of a specified element
问题描述
使用jQuery选择器,可以从另一个选择器中选择不是元素后代的所有元素.
Using a jQuery selector, is it possible to select all elements that are not a descendant of the elements from another selector.
例如,我想选择不是是th
标记的后代的所有a
标记.我现在看到的唯一方法如下:
For example, I would like to select all the a
tags that are not a descendant of a th
tag. The only way I can see to do it right now is as follows:
$('a').filter(function () {
return $(this).closest('th').size() == 0
})
推荐答案
假设您正在寻找后代(因为将a
元素作为th
元素的同级元素不是有效的HTML),可以使用
Assuming you are looking for descendants (since having a a
element as a sibling to th
elements is not valid HTML) you can use the :not
pseudo-selector to do this:
$('a:not(th a)');
这在使用document.querySelectorAll
的现代浏览器中应该是非常快的,但是可能比旧版本的IE慢.
This should be pretty fast in modern browsers using document.querySelectorAll
, but might be slower than the original for older versions of IE.
在此处查看简单的演示: http://jsfiddle.net/JR5sP/
See a simple demo here: http://jsfiddle.net/JR5sP/
这篇关于选择不是指定元素后代的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!