Brayden P. Brayden P. - 5 months ago 11
jQuery Question

Use a variable as a nth selector?

I'm trying to select all elements with class .formRow greater than a defined variable (x). How do I call the variable within the tag?

$(document).ready(function(){
var x = 1;
$('.formRow:nth('x') ~ .formRow').toggleClass('subEdit');

});

Answer

It should be nth-child(). Also, you need to use + to combinate a string with a variable:

$(document).ready(function(){
  var x = 1;
  $('.formRow:nth-child('+x+') ~ .formRow').toggleClass('subEdit');
});

Please note that this isn't a class selector. So, if x=3, it will not select the third .formRow. It will select the third child that also has the .formRow class! If that is what you are looking for, then use

$('.formRow').eq(x)