Is there a way to validate (verify that its constructed correctly) a Sizzle selector without running it?
A pure-JavaScript CSS selector engine designed to be easily dropped in to a host library. More information. Documentation. Browser support.
Sizzle. js is a JavaScript library that implements a "CSS selector engine designed to be easily dropped in to a host library." jQuery uses it internally for its CSS selection needs. If you wanted a CSS engine and had no need for all the other JavaScript benefits of jQuery, you could use Sizzle. js separately.
GitHub - jquery/sizzle: A sizzlin' hot selector engine. Failed to load latest commit information. A pure-JavaScript CSS selector engine designed to be easily dropped in to a host library. In the spirit of open source software development, jQuery always encourages community code contribution.
To help you get started and before you jump into writing code, be sure to read these important contribution guidelines thoroughly: In order to build Sizzle, you should have Node.js/npm latest and git 1.7 or later (earlier versions might work OK, but are not tested). For Windows you have to download and install git and Node.js.
What is the easiest way to validate XPath / CSS selectors? Most of the browsers provide a built-in developer tools, which includes a handy feature that can evaluate or validate XPath/CSS selectors without any third-party extensions: browser console.
Easy-peasy. In the sizzle/dist folder you will find build version of sizzle along with the minified copy and associated map file. Run npm install, it's also preferable (but not necessarily) to globally install grunt-cli package – npm install -g grunt-cli Open test/index.html in the browser.
Well, as Russ says, since Sizzle interprets the selector, it cannot validate it without evaluating it.
However, you can catch the exception thrown by Sizzle to determine if a selector is valid or not:
function isSelectorValid(selector)
{
try {
$(selector);
} catch (x) {
return false;
}
return true;
}
Your can test this solution here.
EDIT: For the sake of history, my original (and overengineered) answer was:
However, it's possible to temporarily override Sizzle's error management in order to extract a boolean value from the error status of its last parse operation. The following solution takes advantage of the fact that jQuery exposes Sizzle through $.find
(so far):
function isSelectorValid(selector)
{
var oldErrorMethod = $.find.error;
try {
$.find.error = function(msg) {
valid = false;
oldErrorMethod(msg);
};
$(selector);
return true;
} catch (x) {
return false;
} finally {
$.find.error = oldErrorMethod;
}
}
That can arguably be considered as a horrible hack, but it works: you can test it here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With