最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jquery get the ID of the great-great-great-great-grandparent - Stack Overflow

programmeradmin4浏览0评论

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
  • 2 $(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
Add a comment  | 

6 Answers 6

Reset to default 12

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/

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.

发布评论

评论列表(0)

  1. 暂无评论