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())].
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
<div id='div1'> <div id='div2'><p></p></div> <div id='div3' class='a'><p></p></div> <div id='div4'><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
What is obtained is div3
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>
(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!