JQuery: parent selector definition and usage

  • 2020-03-30 03:27:37
  • OfStack

: definition and usage of parent selector:

This selector matches elements that contain child elements or text.
Note: Spaces are also included.

Grammatical structure:

$(" parent ")

This selector is typically used in conjunction with other selectors, such as class selectors, element selectors, and so on. Such as:

$(" div: parent "). The animate ({width: "300 px"})

The above code can set the width of a div containing text or elements to 300px.
If you don't use it with other selectors, the default is to use it with a * selector, such as $(":parent") equals $("*:parent").

Example code:

Example 1:


<!DOCTYPE html> 
<html> 
<head> 
<meta charset=" utf-8"> 
<meta name="author" content="http://www.softwhy.com/" /> 
<title> The ant tribe </title> 
<style type="text/css"> 
div{ 
list-style-type:none; 
width:150px; 
height:30px; 
border:1px solid red; 
} 
</style> 
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script> 
<script type="text/javascript"> 
$(document).ready(function(){ 
$("button").click(function(){ 
$("div:parent").animate({width:"300px"}) 
}) 
}) 
</script> 
</head> 
<body> 
<div> I am a text </div> 
<div></div> 
<button> Click to view </button> 
</body> 
</html>

The above code is able to animate the width of a div containing text or elements to 300.

Example 2:


<!DOCTYPE html> 
<html> 
<head> 
<meta charset=" utf-8"> 
<meta name="author" content="http://www.softwhy.com/" /> 
<title> The ant tribe </title> 
<style type="text/css"> 
div{ 
list-style-type:none; 
width:150px; 
height:30px; 
border:1px solid red; 
} 
span{border:1px solid green;} 
</style> 
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script> 
<script type="text/javascript"> 
$(document).ready(function(){ 
$("button").click(function(){ 
$("*:parent").animate({width:"300px"}) 
}) 
}) 
</script> 
</head> 
<body> 
<div> I am a text </div> 
<div></div> 
<span> Hello, everyone </span> 
<button> Click to view </button> 
</body> 
</html>

Since the above code does not specify a selector to work with the :parent selector, it works with the * selector by default, allowing the code to animate the width of an element containing text and elements to 300px in a custom fashion.


Related articles: