Home > Web Front-end > JS Tutorial > body text

How to get parent element using jQuery

不言
Release: 2018-12-26 17:29:59
Original
23142 people have browsed it

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.

How to get parent element using jQuery

.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>
Copy after login

How to get parent element using jQuery code

$(function(){
  $("p").parent("div").css("color","#d9534f");
});
Copy after login

The running results are as follows: When the parent element is a div, it will change its color to red.

How to get parent element using jQuery

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!