I have three <li>
tags in an <ul id="accordion">
. I now want to select the various items via jQuery.
To select the first <li>
item, we can use $("#accordion li:first")
.
To select the last <li>
item, $("#accordion li:last")
works
How can I select the middle <li>
element through a jQuery selector? There is no :middle
pseudo-class that I could use here.
You can combine two ":not" selectors so that you get all of the 'not first, and not last' elements like so:
HTML
<ul>
<li>First</li>
<li>Second</li>
<li>Third</li>
</ul>
Javascript
$('li:not(:first-child):not(:last-child)').css('color', 'red');
Also, check the JsFiddle
There is no :middle
selector, and this makes sense – what element would get matched when we have 4 items?
However, you can access elements by their index. Using CSS Level 3 selectors, you can use the :nth-child(…)
pseudo-class:
#accordion li:nth-child(2)
The :nth-child
pseudoclass can also select repeating patterns of elements, such as all even or odd childs.
jQuery additionally offers the nonstandard :eq(…)
pseudoclass for indexing, which you should probably use in this case:
$("#accordion li:eq(1)") // zero-based indexing
Further reading:
:nth-child
CSS documentation on MDN:nth-child
jQuery documentation:eq
jQuery documentationIf 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