Vince P
Vince P

Reputation: 1791

jQuery + CSS element change

I'm using the following code to set all classes of the element to display:none with the exception of the first instance.

How would I modify the code to set the classes all the elements todisplay:none with the exception of the SECOND instance only.

$(document).ready(function () {
    $('selectorForElement').slice(1).css('display', 'none');
});

Upvotes: 2

Views: 731

Answers (3)

JaredPar
JaredPar

Reputation: 754715

Try the following

$(document).ready(function () { 
    $('selectorForElement:eq(0)').css('display', 'none'); 
    $('selectorForElement:gt(1)').css('display', 'none'); 
});

The :eq(0) selector will select the first element in the selector (index equals 0). The :gt(1) selector will select all items with an index greater than 1 which skips the first and second elements. The result is everything but the second element.

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1038800

A conjunction of :not() and :eq() selectors should do it:

$('.selectorForElement:not(:eq(1))').hide();

Live demo.

Upvotes: 5

Cokegod
Cokegod

Reputation: 8424

$('selectorForElement:eq(0), selectorForElement:gt(1)').css('display', 'none');

Upvotes: 2

Related Questions