4

Is there a way to programmatically check the validity of a javascript/jquery selector?

like .class is ok but .class, is not

programmatically in javascript or any backend language (besides going through jQuery source code)

so in pseudo code

 def selectorErrors(selector)

     // do nasty stuff to the selector
     if valid?
      return nil
    else
      return errors
    end
end
Nick Ginanto
  • 29,034
  • 41
  • 131
  • 227

3 Answers3

7

This should validate 99% of what you can throw at jQuery with far less overhead

function validateQuery(str) {
    try {
        document.querySelector(str);
        return true;
    }
    catch(e) {
        // something here to check WHY it's invalid
    }
    return false;
}

edit: ok, this wont tell you WHAT is wrong with it, but it does (quickly) check the validity - at least you'll only need to check WHY it's invalid, not IF :p

Jaromanda X
  • 1
  • 4
  • 64
  • 78
  • Instead of `document.querySelector(str);` shouldn't it just be: `jQuery(str);`? Because ya, jQuery has some pseudo selectors (':has(), ':eq()', etc...) not supported by `document.querySelector()` method – A. Wolff Jul 26 '15 at 14:11
  • In fact, question isn't clear about it: `Validation of a javascript/css selector` & `javascript/jquery selector` – A. Wolff Jul 26 '15 at 14:14
  • Here’s [a fiddle](http://jsfiddle.net/meqruLzr/1/) based on your method to test selectors for validity. – Jed Fox Dec 11 '15 at 23:39
  • https://stackoverflow.com/q/71303374 – CertainPerformance Mar 01 '22 at 03:30
-2
existOrValid('#a')

function existOrValid(a){

    if (/^[#,.]{0,1}[A-Za-z][0-9A-Za-z\-\._:]*$/.test(a)) {
    alert('valid');
}

}

Works on simple class ,id selectors but needs modification for nested queries

MstfAsan
  • 3,679
  • 2
  • 22
  • 34
-5

$('.a.b')

If you want an intersection, just write the selectors together without spaces in between. So for an element that has an ID of a with classes b and c, you would write:

$('#a.b.c')

Nabi
  • 744
  • 1
  • 9
  • 22