As we have discussed about the parent child relationship.
In this tutorial we will see, how can we get the child of a DOM element using JQuery methods.
The children() Method is used to find all the child elements of an HTML DOM element. Let us understand with the below example.
<html> <head> <title> My First Programme </title> </head> <body> <h1> JQuery </h1> <div> This is for Grand Parent <br/> <span> This is for the Parent <p> This is for child </p> </span> </div> <button> Click Me </button> <script src = "https://cdnjs.cloudflare.com/ajax/libs/JQUERY/3.3.1/jquery.min.js"> </script> <script> $('button').click(function(){ $("div").children().css({"color": "blue"}); }); </script> </body> </html>
So, in the above example, we have a <div>, <span> and <p> which we will be mainly focussing on,
<div> This is for Grand Parent <br/> <span> This is for the Parent <p> This is for child </p> </span> </div>
Below is the structure,
So, the <div> element has a child <span> and <span> has a child <p>.
Now, if you consider the <div> element, <p> is the indirect child of <div>.
$('button').click(function(){ $("div").children().css({"color": "blue"}); });
So, the children() method is going to find the direct and indirect children of <div>. And the color of <span> and <p> gets changed to blue.
The find() Method is used to find all the child elements till the child element specified. Let us understand with the below example.
<html> <head> <title> My First Programme </title> </head> <body> <h1> JQuery </h1> <div> This is for Grand Parent <br/> <span> This is for the Parent <p> This is for child </p> </span> </div> <button> Click Me </button> <script src = "https://cdnjs.cloudflare.com/ajax/libs/JQUERY/3.3.1/jquery.min.js"> </script> <script> $('button').click(function(){ $("div").find("span").css({"color": "blue"}); }); </script> </body> </html>
So, in the above example, we have a <div>, <span> and <p>,
<div> This is for Grand Parent <br/> <span> This is for the Parent <p> This is for child </p> </span> </div>
Below is the structure,
So, in the JQuery statement,
$('button').click(function(){ $("div").find("span").css({"color": "blue"}); });
All we are trying to do is, find the all the children of <div> till <span>.