Suraj
Suraj

Reputation: 930

Get nth-child and act on it :jQuery

The code below only acts upon the last child and it triggers the function for all the other child elements.

$('.streetdog').hide();
$('.cat').mouseenter(function(){
    var $catVal = $(".cat").index(this);
    $('.streetdog:nth-child('+$catVal+')').show();
});

You can see the demo at jsfiddle. Basically I'm trying to trigger the child element of the specific loop and hover of .cat

Upvotes: 0

Views: 4049

Answers (2)

Rob W
Rob W

Reputation: 349262

Use :eq instead of :nth-child. Since the .eq() is more efficient than :eq, use .eq() instead:

$('.streetdog').hide();
$('.cat').mouseenter(function(){
    var $catVal = $(".cat").index(this);
    $('.streetdog').eq($catVal).show();
});

Fiddle: http://jsfiddle.net/rkM8N/1/

$('.streetdog').eq() creates a set consisting of all elements whose classname equals streetdog. Then, .eq(n) returns the nth element in this set.

$('.streetdog:nth-child(' + $catVal + ')') select a .streetdog element which is the $catValth child of its parent. Hence, the elements are only shown when $catVal equals two.

Upvotes: 2

James Allardice
James Allardice

Reputation: 166071

A perfectly good answer has already been given, but as an alternative, if your HTML structure is not going to change, you could use parent to get up to the parent div, and next to get the .streetdog element:

$(".streetdog").hide();
$(".cat").mouseenter(function() {
    $(this).parent().next().show(); 
});

Here's a working example.

The reason that eq works, but nth-child does not is explained by the jQuery docs:

The :nth-child(n) pseudo-class is easily confused with :eq(n), even though the two can result in dramatically different matched elements. With :nth-child(n), all children are counted, regardless of what they are, and the specified element is selected only if it matches the selector attached to the pseudo-class. With :eq(n) only the selector attached to the pseudo-class is counted, not limited to children of any other element, and the (n+1)th one (n is 0-based) is selected.

Upvotes: 1

Related Questions