To get the previous sibling of an element we can use the jQuery prev() method.

$("#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");

Using jQuery to Get and Change the Previous Sibling of an Element

In this example, we will get the previous sibling div of the third div and change its background color. We will also add some simple styles to the divs.

Here is the simple HTML setup.


This is paragraph one.

This is paragraph two.

This is paragraph three.

Change background

We will utilize the jQuery click(), css(), and prev() methods to change the background color of the second div when the button is clicked.

Here is the JavaScript code:

$("#click-me").click(function(){
    $("#div3").prev().css("background", "#c1e9c1");
});

The final code and output for this example of how to get and change the previous sibling of an element using jQuery is below:

Code Output:

This is paragraph one.

This is paragraph two.

This is paragraph three.

Change background

Full Code:

.divs { padding: 20px; border: 1px solid #000; margin-bottom: 10px; }

This is paragraph one.

This is paragraph two.

This is paragraph three.

Change background
<script> $("#click-me").click(function(){ $("#div3").prev().css("background", "#c1e9c1"); }); </script>

Hopefully this article has been useful for you to understand how to use jQuery to get the previous sibling of an element.

Categorized in:

jQuery,

Last Update: March 20, 2024