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

JavascriptJquery

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

You can use the find function:

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

Solution 2 - Javascript

There is a hasClass function

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

Solution 3 - Javascript

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.

Solution 4 - Javascript

Simple Way

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

Solution 5 - Javascript

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');
                }
            });

Solution 6 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSamsquanchView Question on Stackoverflow
Solution 1 - JavascriptTejsView Answer on Stackoverflow
Solution 2 - JavascriptMattPView Answer on Stackoverflow
Solution 3 - JavascriptChristopher RamírezView Answer on Stackoverflow
Solution 4 - JavascriptHitesh ModhaView Answer on Stackoverflow
Solution 5 - JavascriptVince VerhoevenView Answer on Stackoverflow
Solution 6 - JavascriptRune FSView Answer on Stackoverflow