Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery - variable nth-child?

Hey. I want to pass a variable as an argument into an nth-child selector.
This doesn't work:

var position = 5;

$("#daddy > div:nth-child(position)").animate({
    opacity: 0.01,
}, 500);​

Is it possible though? Cheers, Jack

like image 612
jack Avatar asked Aug 24 '10 14:08

jack


People also ask

How to use nth child in jQuery?

jQuery :nth-child() SelectorThe :nth-child(n) selector selects all elements that are the nth child, regardless of type, of their parent. Tip: Use the :nth-of-type() selector to select all elements that are the nth child, of a particular type, of their parent.

How do you pass variables to the nth child?

You can simply use :eq() like following. Taken from the JQuery Docs: jQuery( ":nth-child(index/even/odd/equation)" )

What's the difference between the nth of type () and Nth child () selector?

The nth-of-type is very similar to the nth-child pseudo-class. The main difference is that it specifically considers the type of the element getting selected before checking any other logic. Let's use our example from above but apply nth-of-type instead.

What is nth child in Javascript?

The :nth-child() pseudo-class takes a single argument that describes which elements should be matched. Note that element indices are 1-based when using :nth-child() . You can narrow things down by only matching an element of a specific type, e.g. the second positioned div element. index.js. Copied!


2 Answers

Try:

var position = 5;

$("#daddy > div:nth-child(" + position + ")").animate({
    opacity: 0.01,
}, 500);​
like image 152
Sarfraz Avatar answered Oct 10 '22 14:10

Sarfraz


You need quoting:

var position = 5;

$("#daddy > div:nth-child(" + position + ")").animate({
   opacity: 0.01,
}, 500);​
like image 37
jAndy Avatar answered Oct 10 '22 13:10

jAndy