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

jquery - Get the outer most parent id of the Div in javaScript - Stack Overflow

programmeradmin4浏览0评论

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?

Share Improve this question edited Dec 20, 2013 at 9:30 Dhanu Gurung 8,85811 gold badges49 silver badges60 bronze badges asked Dec 20, 2013 at 9:16 RajaRaja 2191 gold badge7 silver badges16 bronze badges 0
Add a ment  | 

5 Answers 5

Reset to default 5

You 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'));

:)

发布评论

评论列表(0)

  1. 暂无评论