views:

3975

answers:

7

I'd like to check ancestry using two jQuery objects. They don't have IDs, and are only going to be available as jQuery objects (or DOM nodes if you called get()). jQuery's is() only works with expressions, so this code would be ideal but will not work:

var someDiv = $('#div');

$('a').click(function() {
    if ($(this).parents().is(someDiv)) {
        alert('boo');
    }
}

Just want to see if one element is a child of another and I'd like to avoid stepping back into DOM land if possible.

+7  A: 

You can use the index() method to check if an element exists in a list, so would the following work?

var someDiv = $('#div');

$('a').click(function() {
    if ($(this).parents().index(someDiv) >= 0) {
        alert('boo');
    }
}

From #index reference.

Gareth
Perfect Gareth, thank you! I'd up-vote you, but my meager 11 reputation score prohibits me from doing so.
MichaelThompson
A: 

Along those lines, parents() optionally accepts a selector itself:

$('a').click(function() {
  if ($(this).parents("#div").length) {
    alert('boo');
  }
});
Dave Ward
.parents() only accepts the most basic of selectors (i.e. only selectors describing a single element will work - not selectors describing ancetry such as "p strong").
Már Örlygsson
It works fine for what he's trying to do though.
Dave Ward
I simplified my example a bit, so in the actual code I am getting the parent object using stored jQuery references instead of string selectors.
MichaelThompson
A: 

One way would be to use the filter function

$('a').click(function() {
    $(this).parents().filter(function() {
       return this == someDiv[0];
    }).each(function() {
       alert('foo');
    })
}

I think you may also be able to get away with using jQuery.inArray

if ($.inArray( someDiv, $(this).parents() ) ) {
        alert('boo');
}
John C
A: 

Would you not get the result you want from simply using a CSS selector?

$( '#div a' ).click( function() { ... } );
Pistos
+6  A: 

Checking for (this).parents().index(someDiv) >= 0, as @Gareth suggests, will work just fine.

However, using the jQuery ancestry plugin is way faster / more efficient.

Már Örlygsson
Thank you! The ancestry plugin and DOM methods are considerably faster.
MichaelThompson
What about giving us a voteup then? ;-)
Már Örlygsson
A: 

Try this:

var someDiv = $('#div');

$('a').click(function() {
    if ($.inArray($(this).parents().get(), someDiv.get(0)) {
        alert('boo');
    }
}
Pier Luigi
A: 
var $element = $('a');
while ($element && !$element.is('someDiv')) {
   var $element = $element.parent();
};
Jonas Fischer