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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With