I’m doing some jQuery to Vanilla JS conversions on my website. In jQuery I can do this:
$("#nav-menu>ul>li.active").removeClass("active");
which, all in one line, will remove the class ‘active’ from any <li> elements which have it (there would only be one). If no <li> elements have that class, there are no errors and my script continues running.
However, in Vanilla JS, if I do this:
document.querySelector('#nav-menu>ul>li.active').classList.remove('active');
and there are currently no <li> elements with the ‘actove’ class, I get the following error and my script stops running:
Uncaught TypeError: Cannot read prperties of null (reading 'classlist')
I can get around this like so:
var active = document.querySelector('#nav-menu>ul>li.active');
if(active) {
active.classList.remove('active');
}
But I’m wondering if there is a better, shorter way to do this(i.e. select an element if it exists, then do something with it)? Is there a shorthand way or way to do it in fewer lines, etc?
Thanks in advance.
>Solution :
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');