I have some code below:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
var index=5;
$("ul li:last").addClass(function(index) {
console.log(index);
return "item-" + index;
});
});
</script>
</head>
<body>
<ul>
<li>11</li>
<li>12</li>
<li>13</li>
<li>14</li>
</ul>
</body>
</html>
And I see the function(index) quite clearly. However I can’t figure out what it is doing. I do see when the new list is built the last li has the class of item-0 . I alo tried to set a variable index=5 but I cannot pass it in (hoping to make item-5 not item-0 ) So what is up with the index in function(index) is it a getter a setter or what?
The
indexis the index of selected element in jQuery collection, as your selector selects the :last li and there is only one element that is selected, index is0.If you want to modify the classes based on the index you can remove the :last selector:
Or if you want to select the last element and add the class based on it’s index you can try:
Note that index is zero-based and the index of first selected element is 0.