jQuery 基于内部没有 class 的选择器
jQuery selector based on not having class inside
我需要 select 一个基于元素内部不存在的元素。
<div class="person">
<div class="name">Jason</div>
</div>
<div class="person">
</div>
select 第二个 div
和 person
class 我需要做什么。我知道有 has
和 not
属性,我是否需要以某种方式组合它们才能使其正常工作?
您可以用作选择器:
$(".person:not(:has(.name))")
但我建议您改为过滤它:
Because :has() is a jQuery extension and not part of the CSS
specification, queries using :has() cannot take advantage of the
performance boost provided by the native DOM querySelectorAll()
method.
$(".person").filter(function(){
return !$(this).find(".name").length;
})
最简单的 jquery 解决方案 $('.person:empty')
,但第二个 div 必须没有 space
<div class="person">
<div class="name">Jason</div>
</div>
<div class="person"></div>
你可以选择这样的东西,
function getPersonWithNoNameField() {
$('.person').each(function() {
if($(this).find('div.name').length === 0) {
var ele = $(this);
console.log(ele.html());
return ele;
}
});
}
getPersonWithNoNameField();
For your need, you can customise the function to return element which you want.
我需要 select 一个基于元素内部不存在的元素。
<div class="person">
<div class="name">Jason</div>
</div>
<div class="person">
</div>
select 第二个 div
和 person
class 我需要做什么。我知道有 has
和 not
属性,我是否需要以某种方式组合它们才能使其正常工作?
您可以用作选择器:
$(".person:not(:has(.name))")
但我建议您改为过滤它:
Because :has() is a jQuery extension and not part of the CSS specification, queries using :has() cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method.
$(".person").filter(function(){
return !$(this).find(".name").length;
})
最简单的 jquery 解决方案 $('.person:empty')
,但第二个 div 必须没有 space
<div class="person">
<div class="name">Jason</div>
</div>
<div class="person"></div>
你可以选择这样的东西,
function getPersonWithNoNameField() {
$('.person').each(function() {
if($(this).find('div.name').length === 0) {
var ele = $(this);
console.log(ele.html());
return ele;
}
});
}
getPersonWithNoNameField();
For your need, you can customise the function to return element which you want.