How to Get the Children of the $(this) Selector

Have you ever thought of how to get the children of the $(this) selector in JavaScript? If yes, then read on to get the right solution to that issue.

You can use the find() method for getting the children of the $(this) selector with jQuery.

In the example below, the jQuery code selects the child element <img> applying CSS style on it on the click of the parent element <div>.

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the Document</title>
    <script src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
    <style>
      .box {
        padding: 70px;
        border: 8px solid #ccc;
        text-align: center;
      }
      .box img {
        width: 300px;
        border: 5px solid #999;
      }
    </style>
  </head>
  <body>
    <div class="box">
      <img src="/uploads/media/default/0001/05/ba011983828560c9c6aff43876a655d7364933ae.png" alt="w3docs">
    </div>
    <script>
      $(document).ready(function() {
          $(".box").click(function() {
              $(this).find("img").css("border-color", "blue");
            });
        });
    </script>
  </body>
</html>

In case you want to get merely the descendants of the target element, the children() method can be used.

This method only traverses a single level down the tree of the DOM. In contrast, the find() method is capable of traversing down multiple levels to select the descendant elements, such as grandchildren, and so on.

So, the children() method gets a set of elements, involving the overall unique immediate children of the appropriate set of elements.

Its syntax is the following:

selector.children([selector])

The usage of the children() method is demonstrated in the example below:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the Document</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
    <style>
      .green {
        color: green;
      }
    </style>
  </head>
  <body>
    <div>
      <span>Welcome</span>
      <p class="selected">Welcome to W3docs</p>
      <div class="selected">And again welcome</div>
      <p class="biggest">And One Last Time</p>
    </div>
    <script>
      $(document).ready(function() {
          $("div").children(".selected").addClass("green");
        });
    </script>
  </body>
</html>

Description of the Selector Context

In JavaScript, selectors, by default, perform searches inside the DOM, beginning from the document root. An alternative context might be given for the search applying the optional second parameter to the function $(). Whenever the search for the span selector is limited to the context of this, only spans inside the clicked element get the additional class.