views:

396

answers:

6

In jquery can I combine "closest" or Parents() with "hasClass", so it will give me a closest element with given class, if it exists on a page?

var matchingDiv = $(this).closest('div').hasClass('SomeClass')

if ( matchingDiv != null )
{
   //we found matching element now manipulate it

}

I will always have either one matching div element, or none. Thanks.

A: 

Are you asking if this will work or not?

Off the top of my head, I would say that it does, because the jQuery paradigm is based on chaining together jQuery functions.

Vivin Paliath
A: 

doc for closest

var matchingDiv = &(this).closest('.SomeClass')

if ( matchingDiv != null )
{
   //we found matching element now manipulate it

}
andres descalzo
Sounds like he specifically wants a 'div' element with the class.
patrick dw
@patrick, I included the link of the documetacion of "closest", I think @VictorS can view the documentation and complete what you need
andres descalzo
+1  A: 

try this, closest takes a selector:

var matchingDiv = $(this).closest('div.SomeClass')

if ( matchingDiv != null )
{
   //we found matching element now manipulate it

}
kmehta
I've tried it before it doesn't work for the reasons unknown to me, it should imo
Victor
strange, how about this: $(this).parents('div').find('.SomeClass:first')
kmehta
This does not work. You test for null will always be true, even if there was no match.
patrick dw
That seems to be the case, how should I change test then to make it valid?
Victor
@VictorS - I've added an answer with the proper test.
patrick dw
A: 

The difference between closest() and parents() is that parents() can give you more than one element if your selector matches more than one. (for what that's worth here)

Pointy
+3  A: 
var matchingDiv = $(this).closest('div.SomeClass')

if ( matchingDiv.length )
{
   // use length to find if there was a match.
   // closest() will always return an object.
}

If this doesn't work, perhaps post some html. Maybe there's a problem there?

patrick dw
It does work, thanks a lot. Documentation states that it returns null, if no matching elements found
Victor
@Patrick, you could also shorten to just `if (matchingDiv.length)` since 0 will evaluate to `false`
Doug Neiner
@Doug, Very true. More concise and concise is good. Will correct.
patrick dw
@VictorS - Actually the documentation for closest() states ' *The returned jQuery object contains zero or one element* '. (Had to check on that one.) No matter what, you're getting an Object.
patrick dw
+1  A: 

Closest takes a selector so you can do this:

 var matchingDiv = $(this).closest('div.SomeClass')

Your next line is a problem, you should be checking a jQuery result like so:

if ( matchingDiv.length )
{
    //we found matching element now manipulate it
}
Naeem Sarfraz