Home > Web Front-end > JS Tutorial > How to get ancestor elements in jquery

How to get ancestor elements in jquery

coldplay.xixi
Release: 2020-11-30 10:19:45
Original
2478 people have browsed it

Jquery method to obtain ancestor elements: Use the method [parent(exp)] to obtain an element collection containing the unique parent element of all matching elements. The code is [alert($(this).parent()) .next().html())].

How to get ancestor elements in jquery

The operating environment of this tutorial: windows7 system, jquery version 1.2.6. This method is suitable for all brands of computers.

Jquery method to get ancestor elements:

parent is to find the first parent node of the current element, parents is to find all the parent nodes of the current element

Let’s talk about the difference between parent and parents first

It’s not difficult to see literally

  • ##parent refers to getting a list that contains all matching elements A collection of elements whose unique parent element is

  • parents obtains an element set containing the ancestor elements of all matching elements (excluding the root element). Can be filtered by an optional

expression.

It can be seen that the value of parent is very clear, which is the parent element of the current element; parents is the ancestor element of the current element. Examples

are listed below:

<div id=&#39;div1&#39;>
<div id=&#39;div2&#39;><p></p></div>
<div id=&#39;div3&#39; class=&#39;a&#39;><p></p></div>
<div id=&#39;div4&#39;><p></p></div>
</div>
Copy after login

  • $('p').parent() What is obtained is div2, div3, div4

  • $('p').parent('.a')The result is div3

  • $('p').parent().parent()What we get is div1, which is rather strange; however, the characteristics of the Jquery object itself determine that this is feasible

  • $('p').parents()What we get is div1,div2,div3,div4

  • ##$('p ').parents('.a')

    What is obtained is div3

##parent(exp)

Usage: Get a A collection of elements containing the unique parent element of all matching elements.

<script src="jquery-1.2.6.min.js" type="text/javascript"></script>
<script type="text/javascript"> 
    $(document).ready(function() {
        $("#btn1").click(function(){
        alert($(this).parent().next().html());
       });
    });
</script>
Copy after login
Related free learning recommendations:

javascript
(video)

The above is the detailed content of How to get ancestor elements in 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