ドキュメント

Traversing/prev

From jQuery JavaScript Library

Jump to: navigation, search

« Back to Traversing

prev[expr] )

Get a set of elements containing the unique previous siblings of each of the matched set of elements.
Use an optional expression to filter the matched set. Only the immediately previous sibling is returned, not all previous siblings.
Arguments:
expr (Optional)String
An expression to filter the previous Elements with.
Examples:

Find the very previous sibling of each div.

    var $curr = $("#start");
    $curr.css("background", "#f99");
    $("button").click(function () {
      $curr = $curr.prev();
      $("div").css("background", "");
      $curr.css("background", "#f99");
    });

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  
  <script>
  $(document).ready(function(){
    
    var $curr = $("#start");
    $curr.css("background", "#f99");
    $("button").click(function () {
      $curr = $curr.prev();
      $("div").css("background", "");
      $curr.css("background", "#f99");
    });

  });
  </script>
  <style>
  div { width:40px; height:40px; margin:10px;
        float:left; border:2px blue solid; 
        padding:2px; }
  span { font-size:14px; }
  p { clear:left; margin:10px; }
  </style>
</head>
<body>
  <div></div>
  <div></div>
  <div><span>has child</span></div>
  <div></div>
  <div></div>
  <div></div>
  <div id="start"></div>
  <div></div>
  <p><button>Go to Prev</button></p>
</body>
</html>

Find the very previous sibling of each paragraph that has a class "selected".

$("p").prev(".selected").css("background", "yellow");

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  
  <script>
  $(document).ready(function(){
    $("p").prev(".selected").css("background", "yellow");
  });
  </script>
  
</head>
<body>
  <div><span>Hello</span></div>
  <p class="selected">Hello Again</p>
  <p>And Again</p>
</body>
</html>

NameType