jQuery traversal prev() method
jQuery is a collection object. If you want to quickly find the element set of the previous sibling elements immediately adjacent to each element in the specified element set, you can use the prev() method
to understand the node search relationship:
The following is the blue li element with class="item-2", and the red node is its prev sibling node
<ul class="level-3">
<li class="item-1">1</li>
3">3</li>
</ul>
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <title></title> <style> .left { width: auto; height: 150px; } .left div { width: 150px; height: 100px; padding: 5px; margin: 5px; float: left; background: #bbffaa; border: 1px solid #ccc; } a { display: block; } </style> <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script> </head> <body> <h2>prev方法()</h2> <div class="left first-div"> <div class="div"> <ul class="level-1"> <li class="item-1">1</li> <li class="item-2">2</li> <li class="item-3">3</li> </ul> </div> <div class="div"> <ul class="level-2"> <li class="item-1">1</li> <li class="item-2">2</li> <li class="item-3">3</li> </ul> </div> <div class="div"> <ul class="level-3"> <li class="item-1">1</li> <li class="item-2">2</li> <li class="item-3">3</li> </ul> </div> </div> <button>点击:prev无参数</button> <button>点击:prev传递选择器</button> <script type="text/javascript"> $("button:first").click(function() { $('.item-2').prev().css('border', '1px solid red'); }) </script> <script type="text/javascript"> $("button:last").click(function() { //找到所有class=item-2的li //然后筛选出最后一个,加上蓝色的边 $('.item-3').prev(':last').css('border', '1px solid blue'); }) </script> </body> </html>Adding a selector in prev() is to further filter the previous set of elements, such as: eq(1), first, last, :contains("3") , has('p'), add a selector that meets your needs to filter. This is the same as next(), but their functions are different