Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery ancestors using jQuery objects

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.

like image 254
MichaelThompson Avatar asked Oct 28 '08 23:10

MichaelThompson


People also ask

What jQuery method finds an HTML element ancestor?

jQuery parentsUntil() Method The parentsUntil() method returns all ancestor elements between the selector and stop. An ancestor is a parent, grandparent, great-grandparent, and so on.

How do I find a specific parent in jQuery?

The parent() method returns the direct parent element of the selected element. The DOM tree: This method only traverse a single level up the DOM tree. To traverse all the way up to the document's root element (to return grandparents or other ancestors), use the parents() or the parentsUntil() method.


1 Answers

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.

like image 117
Gareth Avatar answered Oct 11 '22 06:10

Gareth