[英]Using jQuery to see if a div has a child with a certain class
I have a div #popup
that is dynamically filled with several paragraphs with the class .filled-text
.我有一个 div
#popup
,它用 class .filled-text
动态填充了几个段落。 I'm trying to get jQuery to tell me if #popup
has one of these paragraphs in it.我试图让 jQuery 告诉我
#popup
中是否包含这些段落之一。
I have this code:我有这个代码:
$("#text-field").keydown(function(event) {
if($('#popup').has('p.filled-text')) {
console.log("Found");
}
});
Any suggestions?有什么建议么?
有一个hasClass函数
if($('#popup p').hasClass('filled-text'))
Use the children funcion of jQuery. 使用儿童的jQuery funcion。
$("#text-field").keydown(function(event) {
if($('#popup').children('p.filled-text').length > 0) {
console.log("Found");
}
});
$.children('').length
will return the count of child elements which match the selector. $.children('').length
将返回与选择器匹配的子元素的数量。
简单的方法
if ($('#text-field > p.filled-text').length != 0)
If it's a direct child you can do as below if it could be nested deeper remove the > 如果它是一个直接的孩子,你可以做如下,如果它可以嵌套更深,删除>
$("#text-field").keydown(function(event) {
if($('#popup>p.filled-text').length !== 0) {
console.log("Found");
}
});
if you have multiple divs with same class and some only have that class you must check each one:如果您有多个具有相同类的 div 并且有些只有该类,则必须检查每个:
$('.popup').each(function() {
if ($(this).find('p.filled-text').length !== 0) {
$(this).addClass('this-popup-has-filled-text');
}
});
In the 10 years since you've asked this question, jQuery has added almost exactly the .has(
function that you described above. It filters the selector it's called on -- and it's faster than using $('.child').parent('.parent')
and potentially running all the way up the DOM.自您提出这个问题以来的 10 年中,jQuery 几乎完全添加了您上面描述的
.has(
function 。它过滤了它所调用的选择器 - 它比使用$('.child').parent('.parent')
更快。 $('.child').parent('.parent')
并可能一直运行到 DOM。
$("#text-field").keydown(function(event) {
if($('#popup').has('p.filled-text').length) {
console.log("Found");
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.