Get index of jquery element - only including certain element types
I have a 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, therefore only related to h2 elements. For example, if I get the index of an element with id = "123", it will return 3, since this is the third h2 in the tree.
I tried this:
$('#123').index('h2'); But that does not work. He still counts other elements at the same level of the DOM structure in the account.
+7
Dan
source share1 answer
You must specify a collection of elements, then use index(<element>) to get the index of this element. Note. The argument must be a jQuery or DOM object. Lines do not work. Note that JavaScript indexes are zero-based, so index 2 actually means the third element.
$("#123").parent().children('h2').index($('#123')) Fiddle: http://jsfiddle.net/2dg2q/
+17
Rob w
source share