I am having some trouble understanding how selectors and indexes work in JQuery. I was hoping to write some functions that manipulate html elements based on class attributes, and I realized that when I try to use the index() method or prevAll().length to get the position of an element within a set of elements, I’m not always getting the expected result.
Below, I have a piece of jquery code that does something for everything with the class .element_list, and then within that something for everything with the class .element_list_item. I have two .element_lists, A and B, and all this does is alert me the indexes of the .element_list_items. For list A, the indexes come back as 0 and 1, as expected. In list B, I added a thead element with no class attribute, so in my mind it shouldn’t be grabbed by my jquery code, but the two .element_list_items come back with indexes of 1 and 2, instead of 0 and 1 as expected.
Why is that? My selector is looking for elements wtih the class .element_list_item and a class equal to the contain .element_list’s ID, so why would the addition of the thead affect the positions of the tbodies?
Any help understanding this is appreciated.
<script language="javascript" type="text/javascript">
$(document).ready(function ()
{
$('.element_list').each(function()
{
var list_id = $(this).attr('id');
var first_item_id = $(this).find('.' + list_id + '.element_list_item:eq(0)').attr('id');
alert('List and first list item: ' + list_id + ' - ' + first_item_id);
$(this).find('.' + list_id + '.element_list_item').each(function()
{
var list_item_id = $(this).attr('id');
var index = $(this).prevAll().length;
alert('List item and its index: ' + list_item_id + ' - ' + index);
});
});
});
</script>
</head>
<body>
<form id="form1" name="form1" method="post" action="" enableviewstate="true">
<br />
<br />
<table class="table_noborder">
<thead>
<tr>
<td>List A</td>
</tr>
</thead>
<tbody id="list_A" class="element_list">
<tr>
<td>
<table>
<tbody id="list_A_item0" class="element_list_item list_A">
<tr>
<td>First Item</td>
</tr>
</tbody>
<tbody id="list_A_item1" class="element_list_item list_A">
<tr>
<td>Second Item</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<td>List B</td>
</tr>
</thead>
<tbody id="list_B" class="element_list">
<tr>
<td>
<table>
<thead>
<tr>
<td>Header</td>
</tr>
</thead>
<tbody id="list_B_item0" class="element_list_item list_B">
<tr>
<td>First Item</td>
</tr>
</tbody>
<tbody id="list_B_item1" class="element_list_item list_B">
<tr>
<td>Second Item</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
using the .index() with no arguments will get it’s index compared to all siblings. You can pass in a selector to for it to check in comparison with the collection
so
but
It can also be done the other way