To get the parent div of an element we can simply use the jQuery parent() method.
$("#div1").parent();
Let’s say we have the following HTML:
We will get the parent div of this paragraph.
If we want to change the background color of only the div that contains the paragraph above, we will use the jQuery parent() method along with the css() method.
$("#div1 p").parent().css("background", "green");
If you are using WordPress, don’t forget to change the $ to jQuery as below:
jQuery("#div1 p").parent().css("background", "green");
Using jQuery to Get and Change the Parent Div of an Element
In this example, we will get the parent div of a paragraph and change its background color. We will also add some simple styles to the divs.
Here is the simple HTML setup.
We will change the background color of the parent div of this paragraph.
Change background
We will utilize the jQuery click(), css(), and parent() methods to change the background color of only the paragraph’s parent div, when the button is clicked.
Here is the JavaScript code:
$("#click-me").click(function(){
$(".divs p").parent().css("background", "#c1e9c1");
});
The final code and output for this example of how to get and change the parent div of an element using jQuery is below:
Code Output:
We will change the background color of the parent div of this paragraph.
Full Code:
We will change the background color of the parent div of this paragraph.
Change background
<script>
$("#click-me").click(function(){
$(".divs p").parent().css("background", "#c1e9c1");
});
</script>
Hopefully this article has been useful for you to understand how to use jQuery to get the parent div of an element.