RGBK
RGBK

Reputation: 2048

jQuery — Variable not recognised but manual input of exact same value is?

Best explained with code:

$(".myParent .myChild:nth-child(3n)").css('border-top-color','#ffffff');

√ Works

myVar = "3n";
$(".myParent .myChild:nth-child(myVar)").css('border-top-color','#ffffff');

X Doesn't work

This is obviously jQuery programming 101... but seriously, why on earth won't that work?! I'm passing on the same thing!

I tried it as > myVar = 3n (no string), obviously that shouldn't work, and it didn't.

Upvotes: 1

Views: 179

Answers (1)

mcgrailm
mcgrailm

Reputation: 17638

you var has to be concatenated

 var myVar = "3n";

 $(".myParent .myChild:nth-child("+myVar+")").css('border-top-color','#ffffff');

Upvotes: 5

Related Questions