Jquery get id of great great great great great grandfather

If I have this line and am wondering if there is a better way to do this.

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

      

Note that the div I'm looking for an id for has a class "MyClass" in case that might help.

Thank.

+3


source to share


6 answers


you can also try closest

to get the attribute like this:

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

      

or the second way



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

      

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

+7


source


Get it all .parents()

and use .eq()

...

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

      


... or a selector :eq()

...

$(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

      

+2


source


var TheID = $('.MyClass').attr('id');

      

or

var TheID = $('#MyClass').attr('id');

      

is this what you mean? which will get the id .MyClass

0


source


you can use .parents

var TheID = $(this).parents(".MyClass").attr('id');

      

0


source


What is your best definition?

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

//jQuery, terse
var TheID = $(this).closest(".MyClass").prop("id");

      

0


source


Is the identifier you are trying to retrieve dynamically and therefore you don't know what it is?

If so, consider assigning a unique CSS class name to your great great grandfather. Then you should be able to do something like this:

$(".MyGreatGreatGreatGrandparentCssClass").attr("id");

Of course, if you do, you may not need a great grandfather.

0


source







All Articles