简体   繁体   中英

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 . I'm trying to get jQuery to tell me if #popup has one of these paragraphs in it.

I have this code:

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

Any suggestions?

You can use the find function:

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

有一个hasClass函数

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

Use the children funcion of jQuery.

$("#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.

简单的方法

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:

            $('.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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM