On modern JavaScript driven or enhanced sites the HTML DOM is sprinkled with events.
Since the birth of HTML5, (and decline of the worst (most expensive) browser ever: Microsoft Explorer) the appropriate way of attaching events is using AddEventListener()
document.querySelector('selector').addEventListener('click', function () { console.log("Hi, you clicked") });
This works only if the queried element does exists. Otherwise you”ll get an error and further execution of the script will fail.
So you’ll need to add a conditional check, the querySelector function returns null when the element can’t be found:
if (document.querySelector('selector'))
document.querySelector('selector').addEventListener('click', function () {
console.log("Hi, you clicked")
});
Modern JavaScript is developing
But functionality to JavaScript is added every year and now there is a optional chaining and that feature is exactly what we need.
Optional chaining was introduced in ES2020. It’s supported by all modern updated browsers.
Optional chaining
Simply add a ? to a object property or method to check if it is existing.
book.author?.name
This will not cause an error if book.author is nullish (not existing)
Using this syntax and arrow functions the new code for attaching an event to an element is:
document.querySelector('selector')?.addEventListener('click', ()=>console.log("Hi, you clicked"));
If the element doesn’t exist, it will not do anything (document.querySelector('selector')
is nullish). It won’t cause an error.
Exactly what we need!