jquery find ancestor element parent () parents () parentsUntil ()

jquery find ancestor element parent () parents () parentsUntil ()

The so-called ancestor elements are the "parent elements" and "grandfather elements" of an element ... Lord element, although there is no such statement in the front end, but it is more vivid, so this section uses this statement.

1. The parent () method

In jQuery, we can use the parent () method to find the "parent element" of the current element. Remember, an element has only one parent element.

parent(expression)

<script type="text/javascript">

         $( function () {
             $( "td" ).hover( function () {
                 $( this ).parent().html( "<p>www.nanaopearl.com</p> " )
             }, function () {
                 $( this ).parent().html( "<p>www.nanaopearl.com</p> " )
             })
         })
     </script>
 

Second, the parents () method

The parents () method is similar to the parent () method, and is used to find the ancestor elements of the selected element. But these two methods also have essential differences.

In fact, these two methods are also easy to distinguish. Parent is in singular form, and there is only one ancestor element to be searched, which is the parent element. And parents is a plural form, and the ancestor elements to be searched are of course all ancestor elements.

<script type="text/javascript">

         $( function () {
             $( "#btn" ).click( function () {
                 var parents = $( "span" ).parents()
                               .map( function () { return this .tagName; })
                               .get().join( "," );
                 alert( "span元素的所有祖先元素为:" + parents.toLowerCase());
             });
         })
     </script>

Three, parentsUntil () method

The parentsUntil () method is a supplement to the parents () method. It can find all the ancestor elements in the specified range, which is equivalent to intercepting some ancestor elements in the parent () method return set.

Guess you like

Origin www.cnblogs.com/96net/p/12719542.html