How do I test CSS selectors in JavaScript?

Poru picture Poru · Feb 6, 2012 · Viewed 13.9k times · Source

How could I test CSS1-3 selectors to check that they get the correct elements, e.g. with JavaScript (maybe jQuery)?

Answer

BoltClock picture BoltClock · Feb 7, 2012

The simplest traditional way by far is to not use JavaScript at all, and just set up a test page by hand where you can test selectors to your heart's content. The test cases you see on the Web (like the well-known CSS3.info Selectors Test) are really just souped-up versions hosted online.

But if you're looking for a JavaScript method, you can try the Selectors API. It's available in modern DOM implementations (IE8+ and others) and it provides a JavaScript frontend for querying the DOM for element nodes using CSS selectors, as well as testing CSS selectors natively supported by a given browser.

(For browsers that don't implement the Selectors API, you'll have to rely on jQuery, but remember that it provides support for a different set of selectors than what a browser supports as well as its own non-standard extensions which aren't found in the Selectors spec. An example of using jQuery with Chrome's JavaScript console to test a selector can be found here.)

Call querySelector() or querySelectorAll() depending on what you want to test, and check the return value (preferably in your browser's developer tools since you're just testing):

  • If matches are found, the former method returns the first Element matched while the latter returns all elements matched as a NodeList.

  • If nothing is found, the former returns null while the latter returns an empty NodeList.

  • If the selector is invalid, an exception will be thrown which you can catch.

Here are some examples with the command editor (multiline) in Firebug's console on Firefox 10, tested on this very question:

  • Finding the first h1 in body:

    var h1 = document.body.querySelector('h1');
    console.log(h1);
    
    <h1 itemprop="name">
    
  • Querying descendants of that h1 element we just found:

    var subnodes = h1.querySelectorAll('*');
    console.log(subnodes[0]);
    
    <a class="question-hyperlink" href="/questions/9165859/how-do-i-test-css-selectors-in-javascript">
    
  • Testing the :-moz-any() pseudo-class in Firefox (:-webkit-any() in Safari/Chrome):

    // This selector works identically to h1 > a, li > a
    var hyperlinks = document.querySelectorAll(':-moz-any(h1, li) > a');
    console.log(hyperlinks);
    
    [a#nav-questions /questions, a#nav-tags /tags, a#nav-users /users, a#nav-badges /badges, a#nav-unanswered /unanswered, a#nav-askquestion /questions/ask, a.question-hyperlink /questio...vascript]
    
  • Testing a nonexistent selector (that perhaps many of us wish did exist):

    // :first-of-class doesn't exist!
    var selector = 'div.answer:first-of-class';
    
    try {
        var firstAnswer = document.querySelector(selector);
        console.log(firstAnswer);
    } catch (e) {
        console.log('Invalid selector: ' + selector);
    }
    
    Invalid selector: div.answer:first-of-class