To get the next sibling of an element we can use the jQuery next() method.
$("#div1").next();
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 next() method along with the css() method.
$("#div1").next().css("background", "green");
If you are using WordPress, don’t forget to change the $ to jQuery as below:
jQuery("#div1").next().css("background", "green");
Using jQuery to Get and Change the Next Sibling of an Element
In this example, we will get the sibling div of the first 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 next() methods to change the background color of the second div when the button is clicked.
Here is the JavaScript code:
$("#click-me").click(function(){
$("#div1").next().css("background", "#c1e9c1");
});
The final code and output for this example of how to get and change the next sibling of an element using jQuery is below:
Code Output:
This is paragraph one.
This is paragraph two.
This is paragraph three.
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(){
$("#div1").next().css("background", "#c1e9c1");
});
</script>
Hopefully this article has been useful for you to understand how to use jQuery to get the next sibling of an element.