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

How to get ancestor elements in jquery

coldplay.xixi
coldplay.xixiOriginal
2020-11-26 11:38:582423browse

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>

  • $('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. <pre class="brush:php;toolbar:false">&lt;script src=&quot;jquery-1.2.6.min.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt; &lt;script type=&quot;text/javascript&quot;&gt; $(document).ready(function() { $(&quot;#btn1&quot;).click(function(){ alert($(this).parent().next().html()); }); }); &lt;/script&gt;</pre> 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!

Statement:
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