I need to build navigation with jQuery by grabbing the current year making it the first nav element. Then building other list items to display the subsequent years… my problem is targeting the siblings of the list items inside of a jQuery function which i want to be able to do so I can easily run that function on multiple pages… here is what I have so far… i can set up a fiddle if it will help just request it.
This is the successful/working code but not wrapped in a jQuery function:
$currentYear = (new Date).getFullYear();
$navListEl = $("#yearNav li").length; // = 7
$lastYear=0;
for (var i=1;i<$navListEl+1;i++)
{
$("#yearNav li"+":nth-child("+i+")").append($currentYear-$lastYear);
$lastYear++;
}
First Try:
jQuery.fn.createNav = function(){
$currentYear = (new Date).getFullYear();
$navListEl = $(this).length; // = 7
alert('hey');
$lastYear=0;
for (var i=1;i<$navListEl+1;i++)
{
$(this+":nth-child("+i+")").append($currentYear-$lastYear);
$lastYear++;
}
}
$("#yearNav li").createNav();
Second Try: (This one works kinda but duplicates the nmbers on each li item instead of once on each)
jQuery.fn.createNav = function(){
$currentYear = (new Date).getFullYear();
$navListEl = $(this).length; // = 7
$lastYear = 0;
for (var i=1;i<$navListEl+1;i++)
{
$(this).append($currentYear-$lastYear);
$lastYear++;
}
}
$("#yearNav li").siblings().createNav();
As an alternative to Musa’s answer, if you want to avoid re-running the selector for every element then you can iterate over the list of selected elements just once with either of these two approaches:
Use the
eq()method in a for loop to access each element in the list by index:Use the
each()method to iterate over each element in turn: