Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Previous siblings selectors for jQuery

If I have a simple HTML list

<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li id="some-id">Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
</ul>

it's easy to select every list item after #some-id:

$("#some-id ~ li")

but how do I select the items before #some-id?

like image 777
Jonas Avatar asked Jul 12 '10 11:07

Jonas


2 Answers

Use .prevAll(), like this:

$("#some-id").prevAll()

For example:

$("#some-id").prevAll().css('color', 'red')​​​​​​​​​​​;​

Give it a try here, there's not a "previous siblings" selector like your next-siblings selector, but .prevAll() will get the elements you want, the same as you could substitute your current selector with $("#some-id").nextAll().

like image 130
Nick Craver Avatar answered Oct 04 '22 01:10

Nick Craver


$("#some-id").prevAll()

See the documentation: http://api.jquery.com/prevAll/

like image 27
Peter Kruithof Avatar answered Oct 04 '22 02:10

Peter Kruithof