Jonah Jonah - 1 year ago 106
jQuery Question

How to get nth row in table with specific class

The below is supposed to get the nth row from a table with the .graphedRow class. It works for the first row, but not the others.

Answer Source

Try using .eq() instead.

$('#someTable tbody .graphedRow').eq(pointIndex+1).css('background-color', '#FEFF9F');

Though it should be noted that eq() starts from 0 for index.

Did a bit of testing in Firebug.

:nth-child is slightly faster than .eq() in this case. (Hundredths of a ms faster)

Also, :nth-child was working fine, but it bases its index on all children of #someTable tbody. It just returns those with the class .graphedRow.

So looking at your JSFiddle, you have 6 <tr> within <tbody> three of which have the class .graphedRow (That would be the 1st, 4th and 6th <tr>) So :nth-child(1), :nth-child(4), :nth-child(6), would select those.

:nth-child's index still increases due to the other children of #someTable tbody (the Other <tr> that don't have the class)

Where-as .eq()'s index is based on however many instances of .graphedRow appear within #someTable tbody

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download