In jquery, you can use the prev() method to query the previous element of a specified element. This method can return the previous sibling element of the selected element. The syntax is "$(selector).prev(filter) "; "filter" is an optional parameter. If set, it can narrow the scope of searching for the previous sibling element.
The operating environment of this tutorial: windows7 system, jquery3.2.1 version, Dell G3 computer.
In jquery, you can use the prev() method to query the previous element of a specified element.
prev() method returns the previous sibling element of the selected element.
Sibling elements are elements that share the same parent element.
Note: This method only returns one element.
Syntax:
$(selector).prev(filter)
Parameter filter: Optional, specifies a selector expression that narrows the scope of the search for the previous sibling element.
Example 1: Return the previous sibling element of each
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <style> .siblings * { display: block; border: 2px solid lightgrey; color: lightgrey; padding: 5px; margin: 15px; } </style> <script src="js/jquery-3.2.1.min.js"></script> <script> $(document).ready(function() { $("li.start").prev().css({ "color": "red", "border": "2px solid red" }); }); </script> </head> <body> <div style="width:500px;" class="siblings"> <ul>ul (父节点) <li>li (兄弟节点)</li> <li>li (类名为"start"的li节点的上一个兄弟节点)</li> <li class="start">li (类名为"start"的li节点)</li> <li>li (兄弟节点)</li> <li>li (兄弟节点)</li> </ul> </div> </body> </html>
Example 2: Select the previous sibling element of each jQuery video tutorial、web front-end development video】 The above is the detailed content of How to query the previous element with jquery. For more information, please follow other related articles on the PHP Chinese website!<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="js/jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function() {
$("div").prev().css("background-color", "yellow");
});
</script>
</head>
<body>
<p>这是一个P元素。</p>
<h2>这是一个标题,并且是div元素的上一个兄弟元素</h2>
<div style="border:1px solid black;padding:10px;">这是一个div元素。</div>
<p>这是另一个P元素。</p>
<p>这是一个P元素,并且是div元素的上一个兄弟元素。</p>
<div style="border:1px solid black;padding:10px;">
<p>这是div里面的一个P元素。</p>
</div>
</body>
</html>