2

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?

Dhanu Gurung
  • 8,480
  • 10
  • 47
  • 60
Raja
  • 209
  • 1
  • 7
  • 16

5 Answers5

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

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
3

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');
koko
  • 958
  • 12
  • 26
0

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

BenM
  • 52,573
  • 26
  • 113
  • 168
  • Read the edited answer... And see the **working** jsFiddle demo. You forgot the selector inside the `parents()` function. – BenM Dec 20 '13 at 09:28
  • To know more about differences between .prop() and .attr() check this http://stackoverflow.com/questions/5874652/prop-vs-attr – Dhanu Gurung Dec 20 '13 at 09:34
-1

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')
iConnor
  • 19,997
  • 14
  • 62
  • 97
-1

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

:)

Suraj Rawat
  • 3,685
  • 22
  • 33