[英]How to check if child element does not have a class using jQuery
I am trying to figure out how to check if a parent div has a child p element without a certain class. 我试图弄清楚如何检查父div是否具有没有特定类的子p元素。
So eg 所以例如
<div id="one" class="item">
<p class="A"></p>
<p class="B"></p>
<p class="C"></p>
</div>
<div id="two" class="item">
<p class="B"></p>
<p class="C"></p>
</div>
If the div does not have ap element with the class "A", I want to hide that div. 如果div没有类“ A”的ap元素,我想隐藏该div。
How would I do this? 我该怎么做?
I tried: 我试过了:
if (jQuery(".item > p.A").length <= 0){
//run code here
}
but that does not seem to work 但这似乎不起作用
Thanks 谢谢
You can use jQuery :has() and :not() like 您可以像这样使用jQuery :has()和:not()
$('div:not(:has(p.A))').hide();
$('div:not(:has(pA))').hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> <div id="one" class="item"> <p class="A">A</p> <p class="B">B</p> <p class="C">C</p> </div> <div id="two" class="item"> <p class="B">B</p> <p class="C">C</p> </div>
Or , you can take an iterative approach 或者 ,您可以采用迭代方法
$('div').each(function() {
if ($(this).has('p.A').length == 0) {
$(this).hide();
}
});
$('div').each(function() { if ($(this).has('p.A').length == 0) { $(this).hide(); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> <div id="one" class="item"> <p class="A">A</p> <p class="B">B</p> <p class="C">C</p> </div> <div id="two" class="item"> <p class="B">B</p> <p class="C">C</p> </div>
Your jQuery code should be: 您的jQuery代码应为:
if ($('.item p').hasClass('A')) {
// statement
}
You can also do something like this. 您也可以这样做。 In my opinion this describes better what you are doing and is easier when you read it back. 在我看来,这可以更好地描述您的工作,并且在您重新阅读时会更容易。 Fiddle: http://jsfiddle.net/ayxdm7y3/ 小提琴: http : //jsfiddle.net/ayxdm7y3/
if ($('div').children().hasClass("A")){
console.log("yes");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.