Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

217
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda