Aung Thet
Aung Thet

Reputation: 3600

Jquery variable of nth-child

How can I index to nth child of a specific jquery object.Like that...

var $parent = $('#slect');
var $index = 4;
var $active = $parent.children().nth-child($index);

I tried this but doesn't work. How can I index from Jquery Object with dynamic variable.

Upvotes: 0

Views: 1056

Answers (3)

Akash Chavda
Akash Chavda

Reputation: 1227

You can use below code

var $parent = $('#slect');
var $index = 4;

if you want to child element 4, so use below script code

var $active = $parent.children().eq($index-1);

in this code "$index-1" using because in "$parent.children()" get result in array so if you use $index so it get 5 element so you should use "$index-1".

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

You can use string concatenation

var $parent = $('#slect');
var $index = 4;
var $active = $parent.children(':nth-child('+$index+')');

Upvotes: 2

Milind Anantwar
Milind Anantwar

Reputation: 82231

as you are only targeting single selectct element, you can use .eq() selector to target children element based on index:

 var $active= $parent.children().eq($index);

Note that the eq selector index is zero-based

Upvotes: 0

Related Questions