[javascript] 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?

This question is related to javascript jquery

The answer is


There is a hasClass function

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

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

Simple Way

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

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.