简体   繁体   中英

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!

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.

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/

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)")

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM