Both the jQuery and Prototpye JavaScript libraries refuse to allow me to use a variable to select an list item element by index number although they accept a hard coded number.

For example, in Prototype this works:


But this will not work no matter how I try to cast the variable as a number or integer:


In jQuery I get similar weirdness. This will work:


But this will not work again even though the value of currentPage is 5 and its type is number:


I'm trying to create a JavaScript pagination system and I need to set the class on the active page button. The list item elements are created dynamically depending upon the number of pages I need.

+4  A: 

Are you certain that currentPage is an integer? Try something like:

var currentPage = 5;

as a simple sanity check. If that works, you should try casting to Integer.

John Millikin
+2  A: 

Make sure that the currentPage variable is correctly scoped in the code where it is being accessed. Could the variable be changed somewhere else in the code before you are accessing it? Tools like Firebug can help you to add a breakpoint at the point of execution and see the value of your variable.

Dan Cramer
+1  A: 

It looks like I just needed to be more specific in my element selector although it is weird that a hard coded number would work.

jQuery('#pagination-digg li').eq(currentPage).addClass("active");