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()
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.
var $element = $('a');
while ($element && !$element.is('someDiv')) {
var $element = $element.parent();
};
Along those lines, parents() optionally accepts a selector itself:
$('a').click(function() {
if ($(this).parents("#div").length) {
alert('boo');
}
});
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.
Would you not get the result you want from simply using a CSS selector?
$( '#div a' ).click( function() { ... } );
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');
}