eithedog eithedog - 5 months ago 13
jQuery Question

jQuery - isSelector function

I've failed to find anything which would be helpful in my particular situation, so here's a question: for a specific string how to check if it's a proper jQuery selector (for time being let's make it simple and restrain ourselves to noncustom jQuery selectors), or if that's too hard, valid CSS selector - basically:

$.isSelector("div") = return true
$.isSelector("* [") = return false - unclosed attribute selector
$.isSelector("* []") = return false - empty attribute selector
$.isSelector("* [name]") = return true
$.isSelector("/hiThere") = return false - invalid / character
$.isSelector("body > ") = return false - > without following child selector
$.isSelector("body > [name=\\\[girls_just_want_to_have_fun\\\]].on a .beach") = return true


Probably there's an internal jQuery function that does the check (or a RegExp), but my voodoo is too poor to find it.

Probably something like this:

function isSelector(string)
{
try
{
$(string);
return true;
}
catch(e)
{
return false;
}
}


would do the trick, but it seems a little extreme.

Cheers!

Answer

I've used this solution:

function isSelector(string)
{
    var ns = document.styleSheets[0];

    if (!ns)
    {
        document.getElementsByTagName('head')[0].appendChild(document.createElement('style'));
        ns = document.styleSheets[0];
    }

    try
    {
        ns.insertRule(string+" {}", 0);
        ns.deleteRule(0);

        return true;
    }
    catch(e)
    {
        return false;
    }
}

Additionally, this (valid) example

isSelector('#\\~\\!\\@\\$\\%\\^\\&\\*\\(\\)\\_\\+-\\=\\,\\.\\/\\\'\\;\\:\\"\\?\\>\\<\\[\\]\\\\\\{\\}\\|\\`\\#')`

returns true