Clinton Jooooones
Clinton Jooooones

Reputation: 1027

How do I find if an element contains a specific class with jQuery?

I need to check if an element contains a certain child class using JQUERY.

I tried:

if ($('#myElement').has('.myClass')) {
   do work son
}

Didn't work.

My html code is laid out like this:

<div id="myElement">
    <img>
    <span>something</span>
    <span class="myClass">Hello</span>
</div>

Upvotes: 11

Views: 11104

Answers (4)

Adam Rackis
Adam Rackis

Reputation: 83358

The easiest way would be to search for .myClass as a child of #myElement:

if($('#myElement .myClass')).length > 0)

If you only want first level children, you'd use >

if($('#myElement > .myClass')).length > 0)

Another way would be passing a selector to find and checking for any results:

if($('#myElement').find('.myClass').length > 0)

Or for first level children only:

if($('#myElement').children('.myClass').length > 0)

Upvotes: 8

Bojangles
Bojangles

Reputation: 101473

Try:

if($('#myElement').children('.myClass').length) {
    // Do what you need to
}

The jQuery object returns an array, which has the .length property. The above code checks if there are any .myClass children in #myElement and, if there are (when .length isn't 0), executes the code inside the if() statement.

Here's a more explicit version:

if($('#myElement').children('.myClass').length > 0) {
    // Do what you need to
}

You could always use $('#myElement .myClass').length too, but $.children() is clearer to some. To find elements that aren't direct children, use $.find() in place of $.children().

Upvotes: 3

Raynos
Raynos

Reputation: 169373

Just use QS

var hasClass = document.getElementById("myElement").querySelector(".myClass");

or you could recurse over the children

var element = document.getElementById("myElement");

var hasClass = recursivelyWalk(element.childNodes, function hasClass(node) {
  return node.classList.contains("myClass");
});

function recursivelyWalk(nodes, cb) {
    for (var i = 0, len = nodes.length; i < len; i++) {
        var node = nodes[i];
        var ret = cb(node);
        if (ret) {
            return ret;
        }
        if (node.childNodes && node.childNodes.length) {
            var ret = recursivelyWalk(node.childNodes, cb);
            if (ret) {
                return ret;
            }
        }
    }
}

Using recursivelyWalk and .classList (which can be shimmed).

Alternatively you can use jQuery

$("#myElement .myClass").hasClass("myClass");

or if you want composite operations without jQuery then try NodeComposite

NodeComposite.$("#myElement *").classList.contains("myClass");

Upvotes: 5

Asterisk
Asterisk

Reputation: 3574

if($.contains($('#myElement'), $('.myClass'))){
    alert("True");
}
else{alert("False")};

Upvotes: 1

Related Questions