I have some code like this:
<h2 id="a">Header</h2>
<table>
<tr>
<td>test</td>
</tr>
</table>
<h2 id="zzz">Header</h2>
<table>
<tr>
<td>test</td>
</tr>
</table>
<h2 id="123">Header</h2>
<table>
<tr>
<td>test</td>
</tr>
</table>
I want to be able to determine, with jQuery, the index of a given h2, excluding all other elements, so only relating to h2 elements. So for example, if I got the index of the item with id="123" it would return 3, as it's the third h2 in the tree.
I've tried this:
$('#123').index('h2');
But it doesn't seem to work. It still counts the other elements at the same level of the DOM structure in the count.
You have to specify the collection of elements, then use index(<element>)
to get the index of the given element. Note: The argument must be a jQuery or DOM object. Strings don't work.
Note that JavaScript indices are zero-based, so an index of 2
actually means the third element.
$("#123").parent().children('h2').index($('#123'))
Fiddle: http://jsfiddle.net/2dg2q/
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