Namespace: Elements:findOne

Elements:findOne

Methods

findOne(node, selectoropt, nullable) → {Node|null}

Searches for and returns one descendant node of a given node matching a CSS selector, just as querySelector.

The main difference to querySelector 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 function is a shorthand for find() with onlyOne being true. The main reason this method existing, is, that querySelector has a 2:1 performance advantage over querySelectorAll and nullish coalescing is easier using a possible null result.

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 element

Source:
See:
Throws:

error if node is not a usable HTML element

Returns:
descendant nodes matching the selector
Type
Node | null
Example
findOne(document.body, 'section ul > li a[href*="#"]');
findOne(element, '> aside img[src]');
findOne(element, 'aside > :scope figcaption');
findOne(element, '*');
findOne(element, '[data-test="foobar"] ~ li a[href]'));