Hello Readers,
difference between find() and children() methods in jquery :
Both find() and childern() are jquery methods.
find() method is used to search the more then one level down the tree (DOM tree) while children() method is uesd to find the single level down the tree.
childern() method is faster than find() method.
Code Example of both find() as well as children() methods are below:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("ul").find("span").css({"color": "red", "border": "2px solid red"});
});
</script>
</head>
<body class="ancestors">body (great-grandparent)
<div style="width:500px;">div (grandparent)
<ul>ul (direct parent)
<li>li (child)
<span>span (grandchild)</span>
</li>
</ul>
</div>
</body>
</html>
In the above code, first we use the find() method which find the all levels down the tree, here we pass span inside the find method so it worked on span and change its color according to CSS property which is given in above code.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("ul").children().css({"color": "red", "border": "2px solid red"});
});
</script>
</head>
<body class="descendants">body (great-grandparent)
<div style="width:500px;">div (grandparent)
<ul>ul (direct parent)
<li>li (child)
<span>span (grandchild)</span>
</li>
</ul>
</div>
</body>
</html>
In the above code, first we use the children() method which find the single level down the tree here we do not pass any argument inside the children method so it worked on current child i.e <li> and change its color according to CSS property which is given in above code.
0 Comment(s)