Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hide everything except the first element with jquery

Tags:

jquery

Is there a one lined way to hide all of a certain type of elements in one selector. I know you could do this:

$('p').hide();
$('p:first(or :eq(0)').show()

Possibly something like this:

$('p:eq(>0)')
like image 808
locrizak Avatar asked Jun 21 '11 15:06

locrizak


2 Answers

slice() will probably give the best performance:

$('p').slice(1).hide();

...where 1 is the second element in the results and 0 would be the first. This is faster because it uses native methods instead of a custom filter.

Alternatively, you could use :not() or .not():

$('p:not(:first)').hide();

//or $('p').not(':first').hide();
like image 182
Andy E Avatar answered Oct 16 '22 01:10

Andy E


http://jsfiddle.net/x6DEY/

$("p").not(":first").hide();

This should work too but is ugly:

$("div:not(:first)").hide();
like image 28
James Montagne Avatar answered Oct 16 '22 02:10

James Montagne