Jquery traverses the difference between parent of and parents of and the parentsUntil of method

  • 2020-03-30 00:43:06
  • OfStack

The parent (the selector) Gets the values of each element in the current set of matched elements The parent element , filtered by a selector (optional).

. Parents (the selector) Gets the values of each element in the current set of matched elements The ancestor element , filtered by a selector (optional).

Given a jQuery object that represents a collection of DOM elements, the.parents() method allows us to search the DOM tree for the ancestor elements of these elements and construct a new jQuery object with matching elements in an order from the most recent parent. The elements are returned in the order from the nearest parent. The.parents() and.parent() methods are similar, except that the latter traverses a single hierarchy up the DOM tree.

Both methods accept an optional selector expression of the same type of argument we passed to the $() function. If the selector is applied, the element is filtered by detecting if the element matches the selector.


Here's a quote


<ul class="level-1">
 <li class="item-i">I</li>
 <li class="item-ii">II
  <ul class="level-2">
   <li class="item-a">A</li>
   <li class="item-b">B
    <ul class="level-3">
     <li class="item-1">1</li>
     <li class="item-2">2</li>
     <li class="item-3">3</li>
    </ul>
   </li>
   <li class="item-c">C</li>
  </ul>
 </li>
 <li class="item-iii">III</li>
</ul>

If we start with item A, we can find its ancestor elements

$('li.item-a').parents().css('background-color', 'red');

As a result of this call, elements such as the level-2 list, item II, and level-1 list (all the way up the DOM tree to < Html>) Set a red background. Since we did not apply the selector expression, the parent element naturally became part of the object. If a selector is applied, the element is checked to see if it matches the selector before it is included. Since we did not apply the selector expression, all ancestor elements are part of the returned jQuery object. If the selector is applied, only the matching items are included.

If we start with project A, we can find the parent element:


$('li.item-a').parent().css('background-color', 'red');

The result of this call is a red background for the level-2 list. Since we did not apply the selector expression, the parent element naturally became part of the object. If a selector is applied, the element is checked to see if it matches the selector before it is included.

Here's an example


<body>body
    <div id="one">one
        <div id="two">hello</div>
        <div id="three">three
            <p>p
               <a href="#">tonsh</a>
           </p>
        </div>
     </div>
</body>

Think about:

$("a").parent()
$("a").parents()
$("a").parents("div:eq(0)")
var id=$("a").parents("div:eq(1)").children("div:eq(0)").html();

Example 3

<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()
$('p').parent('.a')
$('p').parent().parent()
$('p').parents()
$('p').parents('.a')

Take a look at the examples used in previous projects

if(mysql_num_rows($query)){
  while($arr=mysql_fetch_array($query)){
echo <<<admin
          <tr style="text-align:center;">
            <td><input type="checkbox" name="checkbox" value="$arr[id]" /></td>
            <td>$arr[id]</td>
            <td>$arr[log]</td>
            <td>$arr[ip]</td>
            <td>$arr[time]</td>
            <td><form><input type="hidden" name="id" value="$arr[id]" /><span class="del"> delete </span><img src="images/del.gif" /></form></td>
          </tr>
admin;
  }//while end;
}else{
  echo "<tr align=center><td colspan=6> No logon is available </td></tr>";
}

Jquery code

//Delete selected log
$(".delcheckbox").click(function(){
    var str='';
    $(".tab input[name=checkbox]:checked").each(function(){
        str+=$(this).val()+',';
    });
    str=str.substring(0,str.length-1);
    if(chk_Batch_PKEY(str)){
        art.dialog.confirm(' Are you sure to delete the selected log? ',function(){
            $.post("myRun/managerlog_del.php",{id:str},function(tips){
                if(tips=='ok'){
                    art.dialog.through({title:' information ',icon:'face-smile',content:' Delete the success ',ok:function(){art.dialog.close();location.reload();}});
                }else{
                    art.dialog.tips(' Delete failed ');
                }
            });
            return true;
        });
    }else{
        art.dialog.through({title:' information ',icon:'face-sad',content:' Please select the deleted log ',ok:function(){art.dialog.close();}});
    }
}).addClass("pointer");

//del event
$(".del").bind("click",function(event){
    var _tmpQuery=$(this);
    var id=$("input[name='id']",$(this).parents("form:first")).attr("value");
    art.dialog.confirm(' Are you sure to delete the log? ',function(){
        $.post("myRun/managerlog_del.php",{id:id},function(tips){
            if(tips=='ok'){
                art.dialog.tips(' Deleted successfully ');
                _tmpQuery.parents('tr:first').hide();
            }else{
                art.dialog.tips(tips,5);
            }
        });
        return true;
    });
});

Knowledge points involved:

Var id = $(" input [name = 'id'] ", $(this). Parents (" the form: first ")). The attr (" value ");

References:
(link: http://www.w3school.com.cn/jquery/traversing_parent.asp)

(link: http://www.w3school.com.cn/jquery/traversing_parents.asp)


ParentsUntil () method

Definition: parentsUntil() gets the ancestor element of each element in the current set of matched elements until (but not until) the element is matched by the selector, DOM node, or jQuery object.

The parentsUntil() method, as well as the nextUntil() and prevUntil() methods, works the same way. The only difference is that nextUntil() goes down, prevUntil() goes up, and parentsUntil() goes up.

Here's an example:


<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript" src="/jquery/jquery.js"></script>
</head>
<body>
<ul class="level-1 yes">
  <li class="item-i">I</li>
  <li class="item-ii">II
    <ul class="level-2 yes">
      <li class="item-a">A</li>
      <li class="item-b">B
        <ul class="level-3">
          <li class="item-1">1</li>
          <li class="item-2">2</li>
          <li class="item-3">3</li>
        </ul>
      </li>
      <li class="item-c">C</li>
    </ul>
  </li>
  <li class="item-iii">III</li>
</ul>
<script>
$("li.item-a").parentsUntil(".level-1").css("background-color", "red");
$("li.item-2").parentsUntil( $("ul.level-1"), ".yes"  )
  .css("border", "3px solid blue");
</script>
</body>

The results are as follows:

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201312/1351568682_8512.gif ">

Analysis:

$("li.item-a").parentsUntil(".level-1").css("background-color", "red");


<ul class="level-1 yes"> --> Do not meet. It actually fits li.item-a Of the ancestor element. But according to parentsUntil() The method definition does not include selectors, DOM Nodes or jquery Of the element to which the object matches 
  <li class="item-i">I</li>--> No, this is a sibling of its ancestor element. Is not li.item-a The ancestor element. 
  <li class="item-ii">II  --> Conform to the 
    <ul class="level-2 yes"> --> Conform to the 
      <li class="item-a">A</li> --> You start here and you go up to the ancestral elements. 
      <li class="item-b">B
        <ul class="level-3">
          <li class="item-1">1</li>
          <li class="item-2">2</li>
          <li class="item-3">3</li>
        </ul>
      </li>
      <li class="item-c">C</li>
    </ul>
  </li>
  <li class="item-iii">III</li>
</ul>

Let's look at the second statement:

$("li.item-2").parentsUntil( $("ul.level-1"), ".yes"  ).css("border", "3px solid blue");


<ul class="level-1 yes">--> Is its ancestor element   And it satisfies the selector expression ".yes" But according to parentsUntil() The method definition does not include selectors, DOM Nodes or jquery Of the element to which the object matches 
  <li class="item-i">I</li>  Does not match, is not its ancestor element. 
  <li class="item-ii">II--> Is its ancestor element   Does not meet the 
    <ul class="level-2 yes"> --> Is its ancestor element   Satisfies the selector expression ".yes" [ So, finally, match to the node and get the blue border effect shown in the figure above ]
      <li class="item-a">A</li>
      <li class="item-b">B --> Is its ancestor element 
        <ul class="level-3"> --> Is its ancestor element 
          <li class="item-1">1</li>
          <li class="item-2">2</li> --> You start here and you go up to the ancestral elements. 
          <li class="item-3">3</li>
        </ul>
      </li>
      <li class="item-c">C</li>
    </ul>
  </li>
  <li class="item-iii">III</li>
</ul>

Related articles: