Search code examples
javascriptdomdom-manipulationselectors-api

Concise way to search for DOM element and perform action on it if and only if it is found?


I'm performing DOM manipulations using pure JavaScript (no jQuery) in which I need to search for an item, and if it is found, then perform an action on it, for example, clicking it.

I should not do:

document.querySelector('.target-class').click();

...because if the element is not found, then I'll get an error, i.e., Uncaught TypeError: Cannot read property 'click' of null

On the other hand, I could do:

var el = document.querySelector('.target-class');
if (el) {
    el.click();    
}

...but that's creating a variable for a single purpose, and seems wasteful.

On the other hand, this avoids creating a single-purpose variable, but seems overkill:

Array.prototype.forEach.call(document.querySelectorAll('.target-class'), function (element) {
    element.click();
});

This does have the benefit of ensuring that .click() is only performed on a matching DOM element, and not on a NULL. (It is also the only way I can think to perform a series of clicks (or similar operations) on a series of matching elements, not just one element.)

But surely there's a more concise way to search for a single DOM element by attribute, and click() it (or similar operation) if and only if it is found.

Any ideas?


Solution

  • document.querySelectorAll() returns a NodeList, which can be empty, and which has a forEach method:

    So if you wish to apply the same callback on multiple elements, that's all you need (and a polyfill for older browsers).

    onclick = (evt) => console.log( evt.target );
    
    document.querySelectorAll('.target-class').forEach( (el) => el.click() );
    
    document.querySelectorAll('.another-class').forEach( (el) => el.click() );
    <div class="target-class">1</div>
    <div class="target-class">2</div>