jQuery traversa...LOGIN

jQuery traversal parents() method

jQuery is a collection object. If you want to quickly find all the ancestor elements of each element in the collection, you can use the parents() method.

In fact, it is similar to the difference between find and children. Parent will only When searching for one level, parents will search up to the ancestor node

Understand the node search relationship:

<div class="div">
<ul class "son">
" Find the ancestor element div on the li node. Here you can use the $("li").parents() method

parents() no parameters

parents() method allows us to Search for the ancestor elements of these elements, match the elements in order upward, and create a new jQuery object based on the matched elements;

The order of the returned elements starts from their nearest parent element

Note: jQuery is a collection object, so parent is the ancestor element that matches all elements in the collection

The parents() method selectively accepts the same type of selector expression

        Similarly, because jQuery is a collection object, it may be necessary to filter this collection object to find the target element, so it is allowed to pass a selector expression

Notes:

1. The .parents() and .parent() methods are similar, but the latter only performs a single-level DOM tree search
2 The $( "html" ).parent() method returns A collection containing documents, while $( "html" ).parents() returns an empty collection.

Let’s look at a piece of code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script>
</head>

<body>
    <div>php.cn
        <ul>php
          <li>php 中文网</li>
          <li>php 中文网</li>
        </ul>
    </div>
<script>
    $("li").parents().css('color','red');
</script>

</body>
</html>
Next Section
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script> </head> <body> <div>php.cn <ul>php <li>php 中文网</li> <li>php 中文网</li> </ul> </div> <script> $("li").parents().css('color','red'); </script> </body> </html>
submitReset Code
ChapterCourseware