Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get jquery index of element - only including certain types of element

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.

like image 390
Dan Avatar asked Oct 21 '11 15:10

Dan


1 Answers

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/

like image 144
Rob W Avatar answered Oct 29 '22 20:10

Rob W