PolGraphic
PolGraphic

Reputation: 3364

"Which child of its parent am I?" in JQuery

I have the html code:

<div id="all">
    <div id="1">
        <div id="1-1">
        </div>
        <div id="1-2">
        </div>
    </div>
    <div id="2">
        <div id="2-1">
        </div>
    </div>
</div>

I have somewhere in my JQuery code:

var obj = jQuery("#1-2");

I want to check which child of his parent (relative to his parent) is obj (in that case it should return 1 for second index).

I have tried (with no result):

alert(obj.index());

Upvotes: 2

Views: 1510

Answers (3)

Sushanth --
Sushanth --

Reputation: 55750

Try this

var $obj = $("#1-2");

// Need to check th index for this structure

var $parent = $('div > div > div');
// You want to find the index of your selector
// based on the selector that follows the above structure

console.log($($parent).index($obj))

Check Fiddle

Upvotes: 0

thecodeparadox
thecodeparadox

Reputation: 87083

Your code is returning the correct index. I think you just need implement code in jquery ready.

$(function() {
   var obj = jQuery("#1-2");
   alert( obj.index() );
});

DEMO

Upvotes: 6

YashPatel
YashPatel

Reputation: 295

Try This

var obj = jQuery("#1-2");
var parentId = obj.parent().attr('id');

FIDDLE

Upvotes: 0

Related Questions