admin管理员组文章数量:1221307
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.
本文标签: javascriptjquery get the ID of the greatgreatgreatgreatgrandparentStack Overflow
版权声明:本文标题:javascript - jquery get the ID of the great-great-great-great-grandparent - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1739311355a2157597.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
$(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