jquery
  1. jquery-find

JQuery find()

The find() method in JQuery allows you to search for elements that are descendants of a selected element. This can be useful in situations where you want to access specific elements within a larger set of elements.

Syntax

The basic syntax for using find() is as follows:

$(selector).find(filter);

Here, selector is the element that you want to search within, and filter is the criteria that you want to use to filter the results.

Use

The find() method is useful in situations where you want to access specific elements within a larger set of elements. For example, if you have a large list of items and you want to find all of the items that contain a specific keyword, you can use find() to search within each item and return only the ones that match your criteria.

Example

Consider the following HTML code:

<ul class="list">
    <li class="item">Item 1</li>
    <li class="item">Item 2</li>
    <li class="item">Item 3</li>
    <li class="item sub-item">Sub-item 1</li>
    <li class="item sub-item">Sub-item 2</li>
    <li class="item sub-item">Sub-item 3</li>
</ul>

If you wanted to use find() to search for only the sub-items within the list, you could use the following JQuery code:

$('.list').find('.sub-item');

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>jQuery Example</title>
  <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
</head>
<body>

 <ul class="list">
    <li class="item">Item 1</li>
    <li class="item">Item 2</li>
    <li class="item">Item 3</li>
    <li class="item sub-item">Sub-item 1</li>
    <li class="item sub-item">Sub-item 2</li>
    <li class="item sub-item">Sub-item 3</li>
</ul>

  <script>
    $(document).ready(function(){
      var subItems = $(".list").find(".sub-item");

      // Do something with the found sub-items
      subItems.css("color", "blue");
    });
  </script>

</body>
</html>
Try Playground

This code would return all of the elements with a class of sub-item that are descendants of the element with a class of list.

Summary

The find() method in JQuery is a powerful tool that allows you to search for specific elements within a larger set of elements. It can be used to filter results based on a specific criteria, such as class names or element types. By using find(), you can easily access the elements that you need to modify or manipulate, saving you time and effort in your web development projects.

Published on: