jQuery traversal parent() method

jQuery is a collection object. If you want to quickly find the parent element of each element in the collection (this can be understood as the father-son relationship), you can use the parent() method at this time

Because is the parent element, this method will only search one level upward

Understand the node search relationship:

<div class="div">
<ul class="son" >
<li class="grandson">1</li>
</ul>
</div>

Find the parent element div of ul, $ (ul).parent(), is such a simple expression

parent() has no parameters

The parent() method allows us to search for the parent elements of these elements in the DOM tree, Match elements in order and create a new jQuery object based on the matched elements

Note: jQuery is a collection object, so parent is the parent element of each element in the matching collection

parent() 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 An expression of a selector

Let’s look at an example

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

<body>

  <div><p>Hello</p></div>
  <div class="selected"><p>Hello Again</p></div>

<script>
  $("p").parent(".selected").css("background", "yellow");
</script>

</body>
</html>


Continuing Learning
||
<!DOCTYPE html> <html> <head> <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script> </head> <body> <div><p>Hello</p></div> <div class="selected"><p>Hello Again</p></div> <script> $("p").parent(".selected").css("background", "yellow"); </script> </body> </html>
submitReset Code