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
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.
<!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