jQuery API

.find()

.find( selector ) Returns: jQuery

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

  • version added: 1.0.find( selector )

    selectorA string containing a selector expression to match elements against.

  • version added: 1.6.find( jQuery object )

    jQuery objectA jQuery object to match elements against.

  • version added: 1.6.find( element )

    elementAn element to match elements against.

Given a jQuery object that represents a set of DOM elements, the .find() method allows us to search through the descendants of these elements in the DOM tree and construct a new jQuery object from the matching elements. The .find() and .children() methods are similar, except that the latter only travels a single level down the DOM tree.

The first signature for the .find()method accepts a selector expression of the same type that we can pass to the $() function. The elements will be filtered by testing whether they match this selector.

Consider a page with a basic nested list on it:

<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 in the rest 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').

As of jQuery 1.6, we can also filter the selection with a given jQuery collection or element. With the same nested list as above, if we start with:

var $allListElements = $('li');

And then pass this jQuery object to find:

$('li.item-ii').find( $allListElements );

This will return a jQuery collection which contains only the list elements that are descendants of item II.

Similarly, an element may also be passed to find:

var item1 = $('li.item-1')[0];
$('li.item-ii').find( item1 ).css('background-color', 'red');

The result of this call would be a red background on item 1.

Examples:

Example: Starts with all paragraphs and searches for descendant span elements, same as $("p span")

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.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>

Demo:

Example: A selection using a jQuery collection of all span tags. Only spans within p tags are changed to red while others are left blue.

<!DOCTYPE html>
<html>
<head>
  <style>
    span { color: blue; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p><span>Hello</span>, how are you?</p>
  <p>Me? I'm <span>good</span>.</p>
  <div>Did you <span>eat</span> yet?</div>
<script>
  var $spans = $('span');
  $("p").find( $spans ).css('color','red');
</script>

</body>
</html>

Demo:

Example: Add spans around each word then add a hover and italicize words with the letter t.

<!DOCTYPE html>
<html>
<head>
  <style>
  p { font-size:20px; width:200px; cursor:default; 
      color:blue; font-weight:bold; margin:0 10px; }
  .hilite { background:yellow; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p>
  When the day is short
  find that which matters to you
  or stop believing
  </p>
<script>
  var newText = $("p").text().split(" ").join("</span> <span>");
  newText = "<span>" + newText + "</span>";

  $("p").html( newText )
    .find('span')
    .hover(function() { 
      $(this).addClass("hilite"); 
    },
      function() { $(this).removeClass("hilite"); 
    })
  .end()
    .find(":contains('t')")
    .css({"font-style":"italic", "font-weight":"bolder"});

</script>

</body>
</html>

Demo:

Support and Contributions

Need help with .find() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to .find()? Report it to the jQuery core team.

Found a problem with this documentation? Report it on the GitHub issue tracker

  • Anonymous

    To check whether a DOM element is not found, you can check the length:

    var found = $(“p”).find(“span”);
    if (found.length == 0) {

    }

    • Mitur Binesderti

      It might be better to use .size() instead.

      • http://www.learningjquery.com/ Karl Swedberg

        No. Actually it’s better to use .length.

        • Michael

          I believe using size() will do.

          • http://www.learningjquery.com/ Karl Swedberg

            Yes, of course using .size() “will do.” But why in the world would you use it instead of .length? It adds no value and it requires an extra function call. From jquery.js:
            size: function() {
            return this.length;
            }

          • http://zilverdistel.myopenid.com/ zilverdistel

            for abstraction? I’m also using .length …

      • David Rodrigues

        .size() is about 12% slower that .length in V8 engine

        but it is a invisible difference:
        - .length ~0,0000032s each
        - .size() ~0,0000040s each
        :)

    • BasilBear

      Thank you lesgreen – I have been totally flummoxed for the last day trying to find a way to ascertain whether a particular image was within a div. All my other attemps returned true whether the image was or was not there :(

      Much appreciated!

  • Alman66

    This paragraph should explain what's the difference between filter() and find().

  • Bodyscanner

    Which do you prefer – x.find('y') or $('y',x)?
    Is one faster / more syntactically correct than other?

    • Peter

      As it says:

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

      I personally prefer the latter because it is more compact; I suspect it is a millisecond or two slower (as it's an additional function call)

  • Mm

    input:not(:first)

  • http://twitter.com/nimmbl Christopher Tate

    How would one attach a function call to the end of find()? I.E I'm searching through a large number of elements for items with the same class. I'd like to show some sort of loader that tells the user that it's processing the find. After the find is over, I'd like to remove the loader. Is there a better method for doing this?

  • Thesink

    What is the difference between using find():

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

    …and simply doing this:

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

    • http://www.spencerdrager.com Smdrager

      As it says, .find() only looks through the first level down from the parent.

      $('li.item-ii li') will look at all the levels of children.
      So does $(“li”,”li.item-ii”), which is why I am confused that they said they are equivalent.

      .find() is much faster when dealing with a large DOM to search through.

      • http://www.spencerdrager.com Smdrager

        Nevermind… I was thinking of children, which the article mentions.

    • http://twitter.com/jakubri Jakub Ricar

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

      is useful when you already have a jQuery object (passed to function, declared earlier etc.):

      var item = $('li.item-ii');
      // do something
      item.find('li').css('background-color', 'red');

  • Vinh.Luan

    Can this function find checked checkbox like this?

    var actOpts = $('.checkbox_list').find('checked');

    • Abx

      Use .filter

  • Sainthyoga2003

    the sample here only works for me HERE not else where i put the code, i copy and paste the code, but the html is working as xhtml with a div, inside it another div and trying to make the same seeing here but dosen't run

  • Will

    Note that you can't put spaces in the selector like you can with $().
    So where you might use $(“td .note”), you have to use .find(“td.note”).

    • John

      That's because td.note means “the td whose class is note”, whereas td .note means “something whose class is note, inside td.”

      They're two completely different selectors.

  • Kurteknikk

    Anyone can tell me why $('script') works and .find('script') doesn't work ?
    Does it have to do that script is not a physical viewable 'element' ??

  • Matteosistisette

    find(), and apparently all traversing methods, ONLY work on elements that are currently part of the document. Besides the fact that I don't see a good reason for that, it should DEFINITELY be mentioned in the documentation, as it is not obvious at all. Manipulation methods for example _do_ work on elements that have been created, cloned, etc but not inserted into the document. Traversing methods don't: they will always return an empty selection.

    For example, this won't work:

    var x=$(“

    bla bla bla

    <div>foo</div>

    bla bla bla

    “).find(“p”);
    $(“body”).append(x);

    • Matteosistisette

      SORRY – traversing DOES work on elements that are not inserted in the DOM. The reason why my example doesn't work is that the “p”s are at the root level in the html string.

      Feel free to remove these comments of mine if you see fit.

  • Matteosistisette

    Oh shit, the html code in my example got parsed. When will this comment form be improved?

  • Yktd26

    Why find() doesn't work in content loaded by a ajax request

    • http://twitter.com/sp_ sp

      Most probably because you either (a) don't initialize that content as HTML, or (b) call find() before the ajax request receives a response.

      In pseudocode:

      (a) onComplete: function(content) {
      content.find(“#whatever”); // won't work
      $(“#existingElement).html(content);
      $(“#existingElement).find(“#whatever”); // works
      }

      (b) $.ajax(“/path/to/”, data, function(content) {
      $(“#existingElement).append(content);
      $(“#existingElement).find(“#whatever”); // works
      });
      $(“#existingElement”).find(“#whatever”); // won't work because request isn't completed

  • Beont

    $.get(“markers.php”, {area : area, case : arid}, function(xml){
    $(xml).find(“marker”).each(function(){ var name = $(this).find('name').text();
    var address = $(this).find('address').text();
    var lat = $(this).find('lat').text();
    var lng = $(this).find('lng').text();
    var name = $(this).find('name').text();
    .
    }); });
    What am I doing wrong ? its not working on ie

    • Beont

      i also added $(“#markers”).append(xml); and changed to $(“#markers”).find……
      It works in every browser. I am sure that I am doing something wrong. Can anybody tell me what?

      • Beont

        except ie

        • Ralph

          I'm hitting the same issue. there appears to be a problem traversing xml data in Internet Explorer on IE.

          • Ralph

            *Internet Explorer -> jQuery

    • McKnickers

      Look at the following post:
      http://stackoverflow.com/quest…

      The problem may be the content-type the server is sending. If you control the server and are using php, try using:
      header('Content-type: text/xml');

  • Beont

    i also added $(“#markers”).append(xml); and changed to $(“#markers”).find……
    It works in every browser. I am sure that I am doing something wrong. Can anybody tell me what?

  • Beont

    except ie

  • Beont

    except ie

  • Ralph

    I'm hitting the same issue. there appears to be a problem traversing xml data in Internet Explorer on IE.

  • Ralph

    *Internet Explorer -> jQuery

  • McKnickers

    Look at the following post:
    http://stackoverflow.com/quest…

    The problem may be the content-type the server is sending. If you control the server and are using php, try using:
    header('Content-type: text/xml');

  • http://pulse.yahoo.com/_ZCNENNW5YRULFCG5ZUV5HBIOBU Ayal Gelles

    i think it would have been nicer if this would get the element rather than not
    var el = $('<div id=”one”><div id=”two”></div></div>').find(“#one”);

    the reason it doesnt is because “find” disregards the root element – which i think it shouldn't

  • PropertyAnalysis

    Hi,
    I am trying to use this in an animated menu I am creating, but I would need to find only the first appearance of the tag “li” not all of them. Is this possible with find() or do I need to use another function?
    Cheers.

    • lovedager

      try with: .find('li:first') =)