current position:Home>JQuery gets the parent and ancestor elements

JQuery gets the parent and ancestor elements

2021-08-22 05:34:51 mb611f1a641bd18

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

  But first, let me say parent and parents The difference between  

It is not difficult to see literally

parent It means to get a set of elements containing the only parent element of all matching elements .

parents To get a set of elements that contain all the ancestor elements of the matching elements ( Does not contain root element ). It can be done through an optional

Filter the expression .

It can be seen that parent The value of is very clear , Is the parent element of the current element ;parents Is the ancestor element of the current element . Examples are listed below

explain :

<div id='div1'>

<div id='div2'><p></p></div>

<div id='div3' class='a'><p></p></div>

<div id='div4'><p></p></div>

</div>
   
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

$('p').parent() What you get is div2,div3,div4

$('p').parent('.a') What you get is div3

$('p').parent().parent() What you get is div1, This is strange ; however Jquery The characteristics of the object itself determine that this is feasible

.

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

$('p').parents('.a') What you get is div3

parent(exp) usage : Gets a collection of elements that contain a unique parent 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>             
   
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.

 

copyright notice
author[mb611f1a641bd18],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210822053449699R.html

Random recommended