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.
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.
Share Improve this question asked Mar 24, 2012 at 17:47 frenchiefrenchie 51.9k117 gold badges319 silver badges526 bronze badges 1 |6 Answers
Reset to default 12you 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/
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
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");
var TheID = $('.MyClass').attr('id');
or
var TheID = $('#MyClass').attr('id');
is this what you mean? that will get the ID of .MyClass
you can use .parents
var TheID = $(this).parents(".MyClass").attr('id');
Is the id that you are trying to retrieve dynamically generated and so therefore you don't know what it is?
If so, consider assigning a unique CSS class name to the great-great-great grandparent. Then you should be able to do something like this:
$(".MyGreatGreatGreatGrandparentCssClass").attr("id");
Of course, if you do this you may not need the great-great-great grandparent's id.
$(this).closest('.MyClass').attr('id')
if there's no other.MyClass
in between, which there shouldn't. – Jonathan Ong Commented Mar 24, 2012 at 17:50