Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I select the middle of three elements?

Tags:

jquery

css

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.

like image 766
user29762 Avatar asked Feb 11 '23 20:02

user29762


2 Answers

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

like image 110
Ronen Cypis Avatar answered Feb 13 '23 15:02

Ronen Cypis


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 documentation
like image 31
amon Avatar answered Feb 13 '23 14:02

amon