I need to execute a function on an element that may or may not exist in the DOM, using a querySelector (not querySelectorAll, because there will be at most one such element). The most elegant solution I can devise is:
(function (element) {
if (element) {
[business logic of the function]
}
}(document.querySelector([css selector])));
The goal would be not to call the function at all if the querySelector doesn't return an element. (querySelector returns null if no matching element is found.)
My original question lacked clear criteria, and my objections to the responses resulted in the question being closed as being opinion-based. Here's the criteria:
I want to solve this without having to declare a variable external to the routine, e.g., not:
let x = document.querySelector([css selector]);
if (x) {
[business logic on x]
};
I'd like something as elegant as document.querySelectorAll, which returns an iterable NodeList (or null) that does not require testing on the returned data before performing work on it. I.e.,
document.querySelectorAll([css selector]).forEach(function (element) {
[business logic using element]
});
querySelectorAll is overkill here, because I'll have 1 returned element at most, and if nothing is returned, no business logic will be run.
At present, the only way I can see to do it is: pass the returned value to the function, and check in the function whether the return is not falsy before proceeding with the work of the function.
Is there an elegant way not to call the function if the return of the querySelector is not an element?
Again, I don't want to use querySelectorAll, since there will be at most one element that matches the querySelector. The beauty of the current solution is that it relies on an anonymous function, and there's no need to create an explicit variable (with var or let), since the function provides a param for passing.
document.querySelector(...)?.someMethod(...).document.querySelectorAll([selector]).forEach((element) => { [business logic] });If nothing is returned, the function is not invoked. I'm essentially seeking the same kind of elegance forquerySelector.[document.querySelector([selector])].filter(Boolean).forEach(function(element) { [business logic] }):)