Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

220
Views
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:

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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');
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!