jQuery Get Immediately Preceding Sibling

This article explains how to select the immediately preceding sibling of an element using jQuery. You will learn about the .prev() method, its core syntax, how to apply optional filtering selectors, and how it behaves compared to similar jQuery traversal methods.

The jQuery method used to get the immediately preceding sibling of an element is .prev(). It searches only the immediately preceding sibling in the DOM tree, rather than all prior siblings.

Syntax and Basic Usage

The basic syntax for the method is:

$(selector).prev([filter]);

When called on a selected element without any arguments, .prev() returns a jQuery object containing the single element that immediately precedes it within the same parent container.

Consider the following HTML structure:

<ul>
  <li id="item1">First</li>
  <li id="item2">Second</li>
  <li id="item3">Third</li>
</ul>

To target the element immediately before #item3:

$('#item3').prev().css('color', 'red');

In this case, only #item2 will be selected and styled with red text.

Using Optional Selectors

The .prev() method accepts an optional string selector to filter the result. If a selector is provided, jQuery checks whether the immediately preceding sibling matches that selector. If it matches, the element is selected; if it does not match, an empty jQuery collection is returned.

<div class="intro">Introductory text</div>
<span class="highlight">Highlight text</span>
<p id="target">Main paragraph</p>
// This will match because the immediate sibling has the class "highlight"
$('#target').prev('.highlight').addClass('active');

// This will NOT match because the immediate sibling is a span, not a div
$('#target').prev('.intro').addClass('active');

Difference Between .prev() and .prevAll()

It is important not to confuse .prev() with .prevAll().

  • .prev() returns only the single sibling immediately prior to the target.
  • .prevAll() returns all preceding siblings back to the beginning of the parent container.

If you only need to manipulate or inspect the element directly before your target in the DOM hierarchy, .prev() is the standard and most efficient method to use.