jQuery doorzoeken - find() methode

Voorbeeld

Zoek naar alle nakomelingen span-elementen in alle paragrafen en stel hun kleur in op rood:

$("p").find("span").css('color','red');

Try it yourself

Definitie en gebruik

De find() methode haalt de nakomelingen van elk element in de huidige elementenverzameling op, en filtert deze door middel van een selector, een jQuery object of een element.

Syntax

.find(selector)
Parameter Beschrijving
selector String-waarde die de selector expressie bevat die wordt gebruikt om de huidige elementen te matchen.

Uitleg

Als je een jQuery object hebt dat een verzameling DOM-elementen vertegenwoordigt, laat de .find() methode je toe om in het DOM-baum deze elementen en hun nakomelingen te zoeken en een nieuw jQuery object te construeren met de overeenkomende elementen. .find() is vergelijkbaar met .children(), maar het laatste volgt alleen één laag van het DOM-baum.

.find() methode heeft als eerste kenmerk dat het dezelfde soort selector expressie accepteert als de expressie die we doorgeven aan de $() functie. Het zal de elementen filteren door te testen of ze overeenkomen met deze expressie.

Denk na over onderstaande eenvoudige geneste lijst:

<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>

We will start from the list II to find the list items within it:

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

Try it yourself

The result of this survey is that projects A, B, 1, 2, 3, and C have all been set to red background. Even if project II matches the selector expression, it will not be included in the result; only descendants will be matched.

Unlike other tree traversal methods, a selector expression is a required parameter for .find(). If we need to retrieve all descendant elements, we can pass the wildcard selector '*'.

The selector context is implemented by the .find() method; therefore, $('li.item-ii').find('li') is equivalent to $('li', 'li.item-ii').

For jQuery 1.6, we can also use the given jQuery collection or element for filtering. For the nested list above, we write first as follows:

var $allListElements = $('li');

Then pass this jQuery object to the find method:

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

Try it yourself

The above code returns a jQuery collection containing list elements that are descendants of the list II.

Similarly, you can also pass an element:

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

Try it yourself

The result of this call is that project 1 has been set to red background.