On the event "click", I would like to get the index of an element that can be in multiple container. The index position returned should be calculated relatively to its container and not to the body tag.
I wrote an example here: http://jsfiddle.net/zUGcK/
My problem is that when I click on the lines in the second block container, the line index returned are: 3, 4, 5 whereas I would like 0, 1, 2 to be returned.
What should I change in the jquery index() arguments to get 0, 1, 2 returned for each line in both containers?
Thanks
http://jsfiddle.net/zUGcK/
$('.line').click(function()
{
alert('index: '+$(this).index('.container .line'));
});
<div class="container">
<div class="header">block #1</div>
<div class="line">line #0</div>
<div class="line">line #1</div>
<div class="line">line #2</div>
</div>
<div class="container">
<div class="header">block #2</div>
<div class="line">line #0 (index 3 returned instead of 0)</div>
<div class="line">line #1 (index 4 returned instead of 1)</div>
<div class="line">line #2 (index 5 returned instead of 2)</div>
</div>
You can use this to get the index value for elements within it's container
$(function()
{
$('.line').click(function()
{
//alert('index: '+$(this).index('.container .line'));
alert($(this).closest('.container').find('.line').index(this));
});
});
You have to use this syntax of $.index
.index( element )
element The DOM element or first element within the jQuery object to look for.
Working Fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With