I have a field for users to input a CSS selector and I want to check if it's valid (according to css3 specification). I tried to use expressions from css3 specification as suggested in another stackoverflow topic, but it didn't work - the regexp I built just didn't match valid selectors. What I have for now is simply:
try {
document.querySelector(selector);
} catch (e) {
// handle bad input
}
But it doesn't seem like a good solution - querySelector function is designed for getting elements, and checking of selector is just a side effect. Furthermore it doesn't provide any information about what is wrong with the selector.
What I'm looking for is something like document.validateSelector or library for parsing CSS selectors.
.className? Basically, are you prefixing theselectorwith the appropriate identifier forclassorid?tryto pick up an error which is reported by a throw, which is how querySelector reports errors. The only reason to not use this and prefer some other solution is if you wanted details such as the type of error or its character position.