1

On clicking child, I want to know the parent index no. Example, there is a div with 3 ul's when I click on each ul's child, it should show the parent index no. of it's parent. How can I get this?

jQuery:

$('.opSection').on('click','li',function(){

    var num = $(this).parent('ul').index();

    alert(num);

    //alert(chartData.Indices[$(this).index()][$(this).index()]);

    })

HTML:

    <div class="opSection">//parent of all
<dl><dd>
        <ul class="selectGroup" title='allIndia' data-select='1'>
            <li data-index="123" class="c_on">All India</li> // when i click any of li i need 0
        </ul>

        <ul class="selectGroup" title='allIndia' data-select='1'>
            <li data-index="123" class="c_on">All India</li> // when i click this, i need 1
        </ul>
</dd></dl>
    </div>
Matt
  • 74,352
  • 26
  • 153
  • 180
3gwebtrain
  • 14,640
  • 25
  • 121
  • 247

1 Answers1

3
$('.opSection').on('click', 'li', function () {
    alert($(this).parent().index();
});

Note I've used event delegation to improve performance when handling events for multiple elements.

The important parts here is parent() to select the ul, and then index(), which, when passed with no parameters, returns it's position relative to its sibling elements.

EDIT As you've said in your comment that your markup isn't the same as what you posted in the question, try the following instead:

$('.opSection').on('click', 'li', function (e) {
    $(e.delegateTarget).find('.selectGroup').index(this.parentNode);
});

$(e.delegateTarget) is the same (but faster) than $('.opSection'). We then search all descendants (find()) for all the <ul />'s, and use the same index() method to find the position of the one we clicked.

Matt
  • 74,352
  • 26
  • 153
  • 180
  • it give only 0 always. the UL is not direct children of ('.opSection'), it has no.of children, one of the children is UL – 3gwebtrain Apr 05 '12 at 13:25