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

311
Views
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 answers
Answer question

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 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!