.prev() JQ Home  <<  Traversal  <<  .prev()

Previous sibling element retrieval.

Description

The .prev() method is used to retrieve the immediately preceding sibling of each element within the matched set.

Syntax

Signature Description
.prev()Retrieve the immediately preceding sibling of each element within the matched set.
.prev( selector )Retrieve the immediately preceding sibling of each element within the matched set, but only if it matches the specified selector.

Parameters

Parameter Description Type
selectorA string containing a CSS or custom jQuery selector.Selector

Return

A jQuery object either containing the elements matched or empty.

.prev() Example Traversal  <<  Top

Retrieve the immediately preceding sibling of each element within the matched set.

In the example below we select all immediately preceding sibling elements of 'p' elements within the .content section of the page and turn their background colour yellow.



$(function(){
  $('#btn5').on('click', function() {
	$('.content p').prev()
	            .css('backgroundColor', 'yellow');
  });
});

Press the button below to action the above code:

.prev( selector ) Example Traversal  <<  Top

Retrieve the immediately preceding sibling of each element within the matched set, but only if it matches the specified selector.

In the example below we select all immediately preceding 'pre' elements of 'form' elements within the .content section of the page and turn their background colour orange.



$(function(){
  $('#btn6').on('click', function() {
	$('.content form').prev('pre')
	            .css('backgroundColor', 'orange');
  });
});

Press the button below to action the above code:

Related Tutorials

jQuery Basic Tutorials - Lesson 6 - Tree Traversal