jQuery children() Method - CodingTag
×


jQuery children()

1289

  • This jQuery method is used to fetch all the direct children of the selected HTML elements.
  • If we talk about the DOM traversal tree, this method traverses the one level downward of the DOM tree.
  • To traverse the all grandchildren or descendants of the selected element, use find() jQuery method.
  • To traverse only the direct parent element of the selected element, use parent() jQuery method.
  • To traverse the all ancestors up to the root element of the selected element, use parents() jQuery method.

Related Topics:

jQuery parentsUntil
jQuery closest

jQuery children

Syntax:

This method has two different signatures.

$(selector).closest(filter) ;

Parameter description:

  • filter: This parameter is used to represents to narrow down the ancestor search. It can be an expression, element or jQuery object. It is optional.
  • $(selector).children(filter);
  • filter: This parameter is used to represents a selector expression to narrow down the search for children. It is optional.

Example:

In this example we will return the direct children of <div> element.

<html>
<head>
<title> jQuery Example </title>
<script type = "text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<style>
div{
background:pink;
padding:30px;
margin:10px;
font-size:20px;
}
p{
background:yellow;
padding:25px;
margin:10px;
}
span{
background:lightgray;
padding:20px;
margin:10px;
}
b{
background:blue;
padding:15px;
margin:10px;
color:white;
}
button{
background:green;
padding:10px;
color:white;
border:1px solid green;
}
</style>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").children().css("border","2px solid red");
});
});
</script>
</head>
<body>

<h2> jQuery children() method Example</h2>
<div>
div element
<p> p element(direct child)
<span> span element(grandchild)
<b> b element( great grandchild) </b></span></p>
<p> p element(direct child)
<span> span element(grandchild)
<b> b element great grandchild </b></span></p>
</div>
<button>Click Me!</button>
</body>
</html>

Output:

When you click the button,



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments