We can use the jQuery prev method to get the previous sibling(div) of the selected div.

$("#div1").prev();

Let’s say we have the following HTML:

This is paragraph one.

This is paragraph two.

This is paragraph three.

If we want to change the background color of only the div that contains paragraph two, we will use the jQuery prev() method along with the css() method.

$("#div3").prev().css("background", "green");

If you are using WordPress, don’t forget to change the $ to jQuery as below:

jQuery("#div3").prev().css("background", "green");

The jQuery prev() method is very similar to the jQuery next method, it just gets a different sibling.

Using the jQuery prev method to Get and Change the Previous Sibling of a Div

In this example, we will get the previous sibling div of the third div and change its background color. The divs we have will all be boxes. We will add some initial styles to them.

Here is the simple HTML setup.



Change background of second box

We will utilize the jQuery click(), css(), and prev() methods to change the background color of the second div when the button is clicked. In our function, we will generate a random color and then apply that color as the background to the second div. Evertime the user clicks to change the background, a new color should appear.

Here is the JavaScript code:

$("#click-me").click(function(){
  //Create a random color
  var randomColor = "#" + (Math.floor(Math.random()*16777215).toString(16));
  $("#div3").prev().css("background", randomColor);
});

The final code and output for this example of using the jQuery prev method to get and change the previous sibling of a div:

Code Output:

Change background of second box

Full Code:



Change background of second box

Hopefully this article has been useful for you to understand how to use the jQuery prev method.

Categorized in:

jQuery,

Last Update: February 26, 2024