Namespace: Elements:find

Elements:find

Methods

find(node, selectoropt, nullable, onlyOneopt, nullable) → {Array.<Node>|Node|null}

Searches for and returns descendant nodes of a given node matching a CSS selector, just as querySelector(All).

The main difference to querySelector(All) is, that this method automatically scopes the query, making sure, that the given selector is actually fulfilled inside the scope of the base element and not always regarding the whole document. So, basically this implementation always automatically adds :scope to the beginning of the selector if no scope has been defined (as soon as a scope is defined anywhere in the selector, no auto-handling will be done). The function always takes care of handling browsers, that do no support :scope yet, by using a randomized query attribute approach.

The second (minor) difference is, that this function actually returns an array and does not return a NodeList. The reason being quite simple: Arrays have far better support for basic list operations than NodeList. An example: Getting the first found node is straightforward in both cases (item(0) vs. at(0)), but getting the last node becomes hairy pretty quickly since, item() does not accept negative indices, whereas at() does. So, with an array, we can get the last node simple by using at(-1). Arrays simply have the better API nowadays and since the NodeList would be static here anyway ...

The last little difference is, that the base node for this function may not be the document itself, since attribute-based scoping fallback does not work on the document, since we cannot define attributes on the document itself. Just use document.body instead.

Parameters:
Name Type Attributes Default Description
node HTMLElement

the element to search in

selector String <optional>
<nullable>
'*'

the element query selector to apply to node, to find fitting elements

onlyOne Boolean <optional>
<nullable>
false

if true, uses querySelector instead of querySelectorAll and therefore returns a single node or null instead of an array

Source:
See:
Throws:

error if node is not a usable HTML element

Returns:
descendant nodes matching the selector, a single node or null if onlyOne is true
Type
Array.<Node> | Node | null
Example
find(document.body, 'section ul > li a[href*="#"]');
find(element, '> aside img[src]');
find(element, '> aside img[src]', true);
find(element, 'aside > :scope figcaption');
find(element, '*');
find(element, '[data-test="foobar"] ~ li a[href]'));
find(element, 'a[href]').at(-1);