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.

.prev(selector)🡢 jQuery

selector SelectorA string containing a selector expression to match elements against.

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:

  <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>

To select the element that comes immediately before item three:

$("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.

Find the very previous sibling of each div.

<div><span>has child</span></div>
<div id="start"></div>
<p><button>Go to Prev</button></p>
div {
  width: 40px;
  height: 40px;
  margin: 10px;
  float: left;
  border: 2px blue solid;
  padding: 2px;
span {
  font-size: 14px;
p {
  clear: left;
  margin: 10px;
var $curr = $("#start");
$curr.css("background", "#f99");
$("button").click(function () {
  $curr = $curr.prev();
  $("div").css("background", "");
  $curr.css("background", "#f99");

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

<p class="selected">Hello Again</p>
<p>And Again</p>
$("p").prev(".selected").css("background", "yellow");

Looking for a Web Developer?


Hi! I'm Basti, author of this site. If you are looking for a web developer with 15+ years of experience, holla at me!

Be it the good 'ol jQuery, vanilla JS or modern frameworks like Vue and Svelte, front- or backend, I can help you.

Just write me at jobs@jqapi.com :)