Which one is the fastest between children() and find() in jQuery?


The answer to which one is the fastest between children() and find() method depends on the usage. The find() method traverses the entire Dom whereas the children() method gets the immediate children of the node.

jQuery children() method

The children() method is to get the immediate children of the node. The children( [selector] ) method gets a set of elements containing all of the unique immediate children of each of the matched set of elements.

Here is the description of all the parameters used by this method −

  • selector − This is an optional argument to filter out all the childrens. If not supplied then all the childrens are selected.

Example

You can try to run the following code to learn how to work with jQuery children() method:

Live Demo

<html>
   <head>
      <title>jQuery children() method</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>    
      <script>
         $(document).ready(function(){
            $("div").children(".selected").addClass("blue");
         });
      </script>    
      <style>
         .blue {
            color:blue;
         }
      </style>
   </head>
   <body>
   
      <div>
         <span>Hello</span>
         <p class = "selected">Hello Again</p>
         <div class = "selected">And Again</div>
         <p class = "biggest">And One Last Time</p>
      </div>
       
   </body>
</html>

jQuery find() method

The find() method traverses the entire DOM below the node. The jQuery.find() method will return the descendant elements of the selected element.

Example

You can try to run the following code to learn how to work with jQuery.find() method,

Live Demo

<!DOCTYPE html>
<html>
<head>
<style>
.myclass * {
    display: block;
    border: 2px solid red;
    padding: 2px;
    margin: 10px;
    color: red;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("ol").find("span").css({"background-color": "blue", "border": "5px solid yellow"});
});
</script>
</head>

<body class="myclass">body
  <div style="width:500px;">div
    <ol>ol  
      <li>li
        <span>The descendent element</span>
      </li>
    </ol>  
  </div>
</body>

</html>

Updated on: 09-Dec-2019

355 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements