An analysis of the differences between parents of and parent of in jQuery

  • 2020-03-30 04:13:46
  • OfStack

This article analyzes the differences between parents() and parent() in jQuery and shares them with you for your reference. Specific analysis is as follows:

In fact, in jQuery, the concept of functions or selectors is very easy to understand, as long as you have enough proficiency in the API manual to be able to distinguish, the title of the function is actually the same, but let's do some simple introduction here, after all, it may be more convenient.

Parents () function:

This function can get all the parent elements of the matching element. Code example:

$(".mayi").parents().css("color","red");

The above code sets the font color of all parent elements of all elements with a class attribute value of "mayi" to red.
See a complete example of the code:

<!DOCTYPE html> 
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="//www.jb51.net/" />
<title> Counts the number of checked boxes - The home of the script </title>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $(".mayi").parents().css("color","red");
})
</script>
</head>
<body>
<div>
Script house one
  <div>
    Script house one by one
    <span class="mayi"> Welcome to script house </span>
  </div>
</div>
</body>
</html>

The above code sets the font color to red in all parent elements of the span element.

Parent () function:

This function is able to get the first level parent of all matched elements, but not all parents.

The same code at the page code block index 0
  The above code sets the font color to red in the parent element of an element with a class attribute value of mayi.
See the full code:

The biggest difference between the two functions is the return of the parent element, from the name of the function can also be perceived, with s can get all the parent element, no s can only get a parent element, very simple here is not introduced, interested friends can see the relevant article.


Related articles: