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.
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;
}
}