[英]Select elements whose children don't contain specific elements in jQuery
I want to select all divs on a page whose children don't contain an element with a specific class. 我想选择子页面上不包含具有特定类的元素的所有div。
I can select elements whose descendants do contain the class with: 我可以选择其后代确实包含类的元素:
$('div').has('.myClass');
So I just want the inverse of this. 所以我只想要反过来。
I'd use ".filter()": 我用“.filter()”:
var theDivs = $('div').filter(function() {
return $(this).find('.myclass').length === 0;
});
A simple $("div:not(:has(.myClass))")
will do the job. 一个简单的
$("div:not(:has(.myClass))")
将完成这项工作。
How it works internally in jQuery? 它在jQuery内部如何工作?
1) $("div")
- gets all DIVs from the document. 1)
$("div")
- 从文档中获取所有DIV。
2) :not(:has(.myClass))
- These are two statements one nested in another. 2)
:not(:has(.myClass))
- 这两个语句嵌套在另一个语句中。 Now jQuery executes :has(.myClass)
on resulted DIVs in above step and gets all DIVs with class name 'myClass' 现在jQuery执行
:has(.myClass)
在上面的步骤中对结果DIV执行:has(.myClass)
并获取类名为“myClass”的所有DIV
3) :not()
- This pseudo-selector method will be applied on All DIVs from Step 1 against the DIVs resulted from second statement to find DIVs without '.myClass'. 3)
:not()
- 这个伪选择器方法将应用于来自步骤1的所有DIV对抗由第二个语句产生的DIV,以找到没有'.myClass'的DIV。 This is possible by looping through all DIVs from Step 1 and comparing DIVs from second step. 这可以通过循环遍历步骤1中的所有DIV并比较第二步中的DIV来实现。
$('div:not(:has(*>.myClass))');
$('div').has(':not(.myClass)');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.