2

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');
});

3 Answers 3

5

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

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

Live demo.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

2

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.

2 Comments

What would I do to implement this then for the 3rd instance and so on?
@VincePettit I think Darin has the best answer here. His use of :not(eq(1)) allows you to filter out a specific element. Indexes are 0 based so you'd need :not(eq(2)) to filter out the 3rd.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.