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

312
Visualizações
How to prevent Uncaught DOMException when checking selector in document.querySelector

in JavaScript I have code like:

var text = '[0-9]';
if (document.querySelector(text) !== null) {
alert('fail');
}

When I run it, there is an error:

Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '[0-9]' is not a valid selector.

Please how to check if querySelector is valid or invalid without this error?

I want to have ability to write anything to variable "text" and I want the code to alert "failed" when it is not valid selector. Without that error, no matter what variable "text" contains.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use try...catch to prevent the error

let text = '[0-9]';
if (getQuerySelector(text) !== null) {
    alert('fail');
}

function getQuerySelector(txt){
  try {
    return document.querySelector(txt);
  } 
  catch(e) {
    return null;
  }
}
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