Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

211
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda