Michel Joanisse
Michel Joanisse

Reputation: 460

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!

Upvotes: 5

Views: 9092

Answers (4)

Rick
Rick

Reputation: 1391

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/

Upvotes: 2

Leniel Maccaferri
Leniel Maccaferri

Reputation: 102408

For the li case:

// hide all li and then show the first one
$('ul li').hide().filter(':lt(1)').show(); 

The other ones:

$('h1:first');

$('h2:first');

$('p:first');

Upvotes: 0

Narnian
Narnian

Reputation: 3908

I don't know how to do this implicitly, but it's pretty easy to select the first element explicitly:

$("h1:first").show();

To hide all but the first:

$("h1:gt(0)").hide();

And, piggybacking off of Tejs:

 $("h1:gt(0),h2:gt(0),p:gt(0),li:gt(0)")

Upvotes: 0

Tejs
Tejs

Reputation: 41236

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.

Upvotes: 7

Related Questions