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
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.
You can simply use :eq() like following. Taken from the JQuery Docs: jQuery( ":nth-child(index/even/odd/equation)" )
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.
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!
Try:
var position = 5;
$("#daddy > div:nth-child(" + position + ")").animate({
opacity: 0.01,
}, 500);
You need quoting:
var position = 5;
$("#daddy > div:nth-child(" + position + ")").animate({
opacity: 0.01,
}, 500);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With