.prev()


.prev( [selector ] )Returns: jQuery

Description: Get the immediately preceding sibling of each element in the set of matched elements. If a selector is provided, it retrieves the previous sibling only if it matches that selector.

Given a jQuery object that represents a set of DOM elements, the .prev() method searches for the predecessor of each of these elements in the DOM tree and constructs a new jQuery object from the matching elements.

The method optionally accepts a selector expression of the same type that can be passed to the $() function. If the selector is supplied, the preceding element will be filtered by testing whether it match the selector.

Consider a page with a simple list on it:

1
2
3
4
5
6
7
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li class="third-item">list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
</ul>

To select the element that comes immediately before item three:

1
$( "li.third-item" ).prev().css( "background-color", "red" );

The result of this call is a red background behind item 2. Since no selector expression is supplied, this preceding element is unequivocally included as part of the object. If one had been supplied, the element would be tested for a match before it was included.

If no previous sibling exists, or if the previous sibling element does not match a supplied selector, an empty jQuery object is returned.

To select all preceding sibling elements, rather than just the preceding adjacent sibling, use the .prevAll() method.

Examples:

Find the very previous sibling of each div.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>prev demo</title>
<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>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
</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>
<script>
var $curr = $( "#start" );
$curr.css( "background", "#f99" );
$( "button" ).on( "click", function() {
$curr = $curr.prev();
$( "div" ).css( "background", "" );
$curr.css( "background", "#f99" );
});
</script>
</body>
</html>

Demo:

For each paragraph, find the very previous sibling that has a class "selected".

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>prev demo</title>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
</head>
<body>
<div><span>Hello</span></div>
<p class="selected">Hello Again</p>
<p>And Again</p>
<script>
$( "p" ).prev( ".selected" ).css( "background", "yellow" );
</script>
</body>
</html>

Demo: