noclist
noclist

Reputation: 1819

Get all elements that contain a particular descendant

I'm trying to loop through all <li> tags that contain the class .fas using the jQuery contains() method and perform some stuff on each one.

$('li:contains(".fas")').each(function (index) {
    //stuff
}

I keep getting the reference error that contains is not defined. Am I using this method incorrectly?

Upvotes: 0

Views: 143

Answers (3)

Mark Schultheiss
Mark Schultheiss

Reputation: 34168

Your question ambiguity leaves me to cross answer this.

First off:

$('li.fas') 

That says to the sizzle engine: Get all elements that have class fas, then reduce that to elements of li (that have that class)

With a space in between this says:

$('li .fas')

Get all elements that have a class fas, then reduce to those that are a decedent of an li element.

$('li>.fas')

Get all elements that have class fas, then reduce that do a set that are direct children of an li element.

The other answer has the .has() so I will not repeat that.

Filter: (basically same as :has() in this case

$('li').filter(function(){
    // reduce the li set; return true when a descendant has the 'fas' class
    return !!$(this).find('.fas').length;
});

More on context here: https://stackoverflow.com/a/16423239/125981

Upvotes: -1

Taplar
Taplar

Reputation: 24965

Another way to do this would be to flip your logic.

$('.fas').closest('li');

You could find all the fas and then find their parent lis.

Upvotes: 1

isherwood
isherwood

Reputation: 61083

You want has().

$('li:has(".fas")').each(function (index) {
    //stuff
}

https://api.jquery.com/has/

Upvotes: 1

Related Questions