Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery get the ID of the great-great-great-great-grandparent

If I have this line and I'm wondering if there's better way to do it.

var TheID = $(this).parent().parent().parent().parent().parent().attr('id');

Note that the div for which I'm looking for the ID has class "MyClass", if that can help.

Thanks.

like image 515
frenchie Avatar asked Mar 24 '12 17:03

frenchie


People also ask

How can I get the ID of an element using jQuery?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

Where can I find grandparents in jQuery?

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.

Which jQuery method returns the direct parent element of the selected element?

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.


3 Answers

you can also try closest for get attribute like this :

 $(this).closest('div.Myclass').attr('id');

or second way is

$(this).parents('div.Myclass').attr('id')

see here : http://jsfiddle.net/sKqBL/10/

like image 193
Jignesh Rajput Avatar answered Sep 28 '22 06:09

Jignesh Rajput


Get all the .parents(), and use .eq()...

$(this).parents().eq(5).attr('id');

...or the :eq() selector...

$(this).parents(':eq(5)').attr('id');

...or make a function...

function up(el, n) {
    while(n-- && (el = el.parentNode)) ;
    return el;
}

...and use it like this...

up(this, 5).id
like image 35
user1106925 Avatar answered Sep 28 '22 08:09

user1106925


What is your definition of better?

//POJS, fastest
var TheID = this.parentNode.parentNode.parentNode.parentNode.parentNode.id;

//jQuery, terse
var TheID = $(this).closest(".MyClass").prop("id");
like image 40
Dennis Avatar answered Sep 28 '22 07:09

Dennis