Home >Web Front-end >JS Tutorial >How to get parent element using jQuery
We have three ways to get the parent element with jQuery, .parent(), .parents(), and .closest(). Below we will introduce these three ways of getting the parent element with jQuery and a specific example.
.Parent()
parent() method returns the direct parent element of the selected element.
In the example presented below, I will use this method. If a tag is specified as a parameter, it will only be returned if it is a parent element that matches the tag.
.parents()
The parents() method returns not only the parent element, but also all ancestor elements of the selected element.
If a tag is specified as a parameter, get all elements matching that parameter.
.closest()
closest() method returns the first ancestor element of the selected element.
If you want to apply a specific style to a parent element, you can use closest().
Let’s look at a specific example
We use the Parent() method to get the parent element
The code is as follows:
HTML Code
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script type="text/javascript" src="http://code.jquery.com/jquery-3.1.0.min.js"></script> <script src="sample.js" type="text/javascript"></script> <title>jQuery</title> </head> <body> <div> <p>这是一个div元素。</p> </div> <p>不是div元素。</p> <div> <p>是div元素。</p> </div> <p>不是div元素。</p> <div> <p>是div元素。</p> </div> <p>不是div元素。</p> </body> </html>
How to get parent element using jQuery code
$(function(){ $("p").parent("div").css("color","#d9534f"); });
The running results are as follows: When the parent element is a div, it will change its color to red.
This article ends here. For more exciting content, you can pay attention to the relevant column tutorials on the PHP Chinese website! ! !
The above is the detailed content of How to get parent element using jQuery. For more information, please follow other related articles on the PHP Chinese website!