Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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');
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading