Javascript 使用 jQuery 查看 div 是否具有某个类的子项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10539162/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:45:52  来源:igfitidea点击:

Using jQuery to see if a div has a child with a certain class

javascriptjquery

提问by Samsquanch

I have a div #popupthat is dynamically filled with several paragraphs with the class .filled-text. I'm trying to get jQuery to tell me if #popuphas one of these paragraphs in it.

我有一个 div#popup动态填充了几个带有 class 的段落.filled-text。我试图让 jQuery 告诉我其中是否#popup有这些段落之一。

I have this code:

我有这个代码:

$("#text-field").keydown(function(event) {
    if($('#popup').has('p.filled-text')) {
        console.log("Found");
     }
});

Any suggestions?

有什么建议?

回答by Tejs

You can use the findfunction:

您可以使用查找功能:

if($('#popup').find('p.filled-text').length !== 0)
   // Do Stuff

回答by MattP

There is a hasClassfunction

有一个hasClass函数

if($('#popup p').hasClass('filled-text'))

回答by Christopher Ramírez

Use the childrenfuncion of jQuery.

使用jQuery的children函数。

$("#text-field").keydown(function(event) {
    if($('#popup').children('p.filled-text').length > 0) {
        console.log("Found");
     }
});

$.children('').lengthwill return the count of child elements which match the selector.

$.children('').length将返回与选择器匹配的子元素的计数。

回答by Hitesh Modha

Simple Way

简单的方法

if ($('#text-field > p.filled-text').length != 0)

回答by Rune FS

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");
? ? ?}
});