jQuery

jQuery – find(selector) Method

In this post, I will show you what is find() method in jQuery with example.

Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

A descendant is a child, grandchild, great-grandchild, and so on.

The DOM tree: This method traverse downwards along descendants of DOM elements, all the way down to the last descendant. To only traverse a single level down the DOM tree (to return direct children), use the children() method.

Note: The filter parameter is required for the find() method, unlike the rest of the tree traversal methods.

Tip: To return all of the descendant elements, use the “*” selector.

Syntax

Here is the simple syntax to use this method −

selector.find( selector )
<ul class="level-1">
  <li class="item-i">I</li>
  <li class="item-ii">II
    <ul class="level-2">
      <li class="item-a">A</li>
      <li class="item-b">B
        <ul class="level-3">
          <li class="item-1">1</li>
          <li class="item-2">2</li>
          <li class="item-3">3</li>
        </ul>
      </li>
      <li class="item-c">C</li>
    </ul>
  </li>
  <li class="item-iii">III</li>
</ul>

If we begin at item II, we can find list items within it:

$( "li.item-ii" ).find( "li" ).css( "background-color", "red" );

The result of this call is a red background on items A, B, 1, 2, 3, and C. Even though item II matches the selector expression, it is not included in the results; only descendants are considered candidates for the match.

Unlike most of the tree traversal methods, the selector expression is required in a call to .find(). If we need to retrieve all of the descendant elements, we can pass in the universal selector '*' to accomplish this.

Selector context is implemented with the .find() method; therefore, $( "li.item-ii" ).find( "li" ) is equivalent to $( "li", "li.item-ii" ).

Example

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>find demo</title>
  <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
</head>
<body>
 
<p><span>Hello</span>, how are you?</p>
<p>Me? I'm <span>good</span>.</p>
 
<script>
$( "p" ).find( "span" ).css( "color", "red" );
</script>
 
</body>
</html>

Result:

Hello, how are you?
Me? I’m good.

Shaiv Roy

Hy Myself shaiv roy, I am a passionate blogger and love to share ideas among people, I am having good experience with laravel, vue js, react, flutter and doing website and app development work from last 7 years.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button