We can use the jQuery parent method to get the parent element(div) of the selected div.
$("#p1").parent();
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 can use the jQuery parent() method along with the css() method.
$(".p2").parent().css("background", "green");
If you are using WordPress, don’t forget to change the $ to jQuery as below:
jQuery(".p2").parent().css("background", "green");
Using the jQuery parent Method to Get and Change the Parent Div
In this example, we will get the parent of any div with a paragraph in it and change its background color. We will also add some simple styles to the divs.
Here is the simple HTML setup.
This is some text.
This is some text.
This is some text.
Change background
We will utilize the jQuery click(), css(), and parent() methods to change the background color of any div with a paragraph in it when the button is clicked. In our function, we will generate a random color and then apply that color as the background to the 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));
$("#top-div p").parent().css("background", randomColor);
});
The final code and output for this example of using the jQuery parent method to get and change the parent div:
Code Output:
This is some text.
This is some text.
This is some text.
Full Code:
This is some text.
This is some text.
This is some text.
Change background
Hopefully this article has been useful for you to understand how to use the jQuery parent method.