jQuery .prevAll() gets all preceding siblings of each element in the set of matched elements

Syntax and Description

.prevAll([selector])

Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector. selector (optional) is a string containing a selector expression to match elements against. Its return value is the new jQuery object.

Get all previous tags and set styles

The following code get all previous tags and then set styles.


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){<!--   w w w.j av a 2  s.  c  om-->
             $("div").prevAll().css("background", "yellow");
        });
    </script>
  </head>
  <body>
    <body>
          <div>java2s.com</div>
          <div>java 2s.com</div>
          <div>java2s.c om</div>
          <div class="selected">java2s.c om</div>
          <div>ja va2s.com</div>
  </body>
</html>

Click to view the demo

Locate all the divs before the last and give them a class


<!--from ww  w  .  j  a va 2s .  co m-->
<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
             $("div:last").prevAll().css("color","red");
        });
    </script>
    <style>
      .selected { color:blue; }
    </style>
  </head>
  <body>
    <body>
        <div>java2s.com</div>
        <div>java2s.com</div>
        <div>java2s.com</div>
        <div>java2s.com</div>
    </body>
</html>

Click to view the demo





















Home »
  jQuery »
    jQuery Tutorial »




Basics
Selector
DOM
Event
Effect
Utilities