jQuery .prev() method gets the immediately preceding sibling of each element in the set of matched

Syntax and Description

.prev([selector])

gets the immediately preceding sibling 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 the previous element and set style

The following code gets the previous element for div and sets its style.


<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 a  v a2  s . c  o  m-->
             $("div").prev(".selected").css("background", "yellow");
        });
    </script>
  </head>
  <body>
    <body>
          <div class="selected">java2s.com</div>
          <div>java2s.com</div>
  </body>
</html>

Click to view the demo

Set the previous element in click event handler

The following code sets the color for previous element in the click event handler.


<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.jav a 2s .  co  m-->
            var $curr = $("#start");
            $curr.css("color", "#f99");
            $("button").click(function () {
                 $curr = $curr.prev();
                 $("div").css("color", "");
                 $curr.css("color", "#f99");
            });
        });
    </script>
  </head>
  <body>
    <body>
          <div>java2s .com</div>
          <div>java2 s.com</div>
          <div>java 2s.com</div>
          <div>jav a2s.com</div>
          <div>ja va2s.com</div>
          <div>j ava2s.com</div>
          <div id="start">java2s.com</div>
          <div>java2s.com</div>
          <button>Go to Prev</button>
  </body>
</html>

Click to view the demo





















Home »
  jQuery »
    jQuery Tutorial »




Basics
Selector
DOM
Event
Effect
Utilities