Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery + How can I select only the first instance of each element?

take the following html for example:

<h1>Level 1 Header</h1>
<h1>My Second Level 1 Header</h1>
<h1>And a third for kicks</h1>

<h2>Level 2 Header</h2>
<h2>2nd Level 2 Header</h2>

<p>Here is a paragraph.</p>
<p>Here is a paragraph number 2.</p>
<p>And paragraph number 3.</p>

<ul>
<li>list item 1<li>
<li>list item 2<li>
<li>list item 3<li>
<li>list item 4<li>
</ul>

How can I select only the first instance of each element?

I'm looking to hide all, in exception to "first" of each element.

Thanks in advance!

like image 941
Michel Joanisse Avatar asked Aug 30 '11 21:08

Michel Joanisse


2 Answers

You should be able to do something like this:

 $('h1:first,h2:first,p:first,li:first')

To select the first element of each set into a jQuery set.

like image 165
Tejs Avatar answered Oct 20 '22 00:10

Tejs


For best performance, avoid non-standard selectors, as they will force the Sizzle selector engine into the slower non-querySelectorAll code branch. Examples of non-standard selectors can be found here: http://api.jquery.com/category/selectors/ (look for any selector that starts with ":")

With that in mind, you can apply the strategy to your use cases as follows:

$("h1").hide().eq(0).show();

$("h2").hide().eq(0).show();

$("p").hide().eq(0).show();

$("ul li").hide().eq(0).show();

For bonus performance improvements, replace hide()/show() with addClass()/removeClass() that adds and removes a class that defines display state changes.

For even more performance improvements, use :first-child whenever/wherever possible: http://www.w3.org/TR/CSS2/selector.html#first-child

Live example: http://jsfiddle.net/rwaldron/w4Wz4/

like image 41
Rick Avatar answered Oct 20 '22 00:10

Rick