admin管理员组文章数量:1398786
Hi in my case I have use the div in the following structure.
<div id="Parent1">
<div>
<div>
<div id="mychildDiv"></div>
</div>
</div>
</div>
My working scenorio:
I know the id of the child div, from that how to get the parent id. For Expample in this, want to get the id Parent1
. Is it possible get the outer most parent id?
Hi in my case I have use the div in the following structure.
<div id="Parent1">
<div>
<div>
<div id="mychildDiv"></div>
</div>
</div>
</div>
My working scenorio:
I know the id of the child div, from that how to get the parent id. For Expample in this, want to get the id Parent1
. Is it possible get the outer most parent id?
5 Answers
Reset to default 5You can use .parents()
to get all the parents of the source element. And then you can get the target parent's id by using .last()
. Please read more about parents() and last()
Try,
$('#mychildDiv').parents('div').last().attr('id')
DEMO
You can do this with a simple css selector, it gets you the first parent that has an id-attribute:
$('#mychildDiv').parents('[id]:eq(0)');
The outmost parent would be:
$('#mychildDiv').parents('[id]:last');
You can use the parents()
and last()
functions:
var parentId = $('#mychildDiv').parents('div').last().prop('id');
Please note correct usage of prop()
, rather than attr()
...
You also need to pass a selector to the parents()
function, otherwise jQuery will return the <body>
element:
jsFiddle Demo
Well, technically if you're looking for the "most outer parent" it will always be body
, and it doesn't make sense to look for the closest parent with a id
attribute.
Why not add some better and self explanatory markup like so.
<div data-outer-parent="true">
<div>
<div>
<div id="myChildDiv"></div>
</div>
</div>
</div>
Then you can do
$('#myChildDiv').parents('[data-outer-parent="true"]:first')
The problem is simple and can be handled via css3 selectors
here is a code in one line :
alert($('#mychildDiv').parents('[id]:last').attr('id'));
:)
本文标签: jqueryGet the outer most parent id of the Div in javaScriptStack Overflow
版权声明:本文标题:jquery - Get the outer most parent id of the Div in javaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744194462a2594671.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论