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?

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

:)

本文标签: jqueryGet the outer most parent id of the Div in javaScriptStack Overflow