More efficient way to select element if it exists, then do something with it in vanilla JavaScript

Solution 1:

You can use optional chaining for this purpose, which can access properties or go into a chained function call only if the expression on the left is not undefined nor null.

document.querySelector('#nav-menu>ul>li.active')?.classList.remove('active');