Javascript Selector API – Should I care?

Posted on April 09, 2012 at 12:09 pm in Development, Training

What is it?

Using JavaScript with CSS selectors, particularly Classes has traditionally been a little awkward. You end up needing dozens of lines of code with fun stuff like regular expressions to do something simple like toggle a Class. Looking for a better way to do this is how many of us got introduced to jQuery and it’s easy access to the DOM.

The JavaScript API has showed up to the party by implementing the W3C Selectors API.

What does it look like?

It looks a lot like jQuery.

The following example would select all p elements in the document that have a class of either “error” or “warning”.

var alerts = document.querySelectorAll("p.warning, p.error");

(Example above taken from the API Examples)

I’ve created a demo that shows this example in action. It uses the classList property  so don’t try this in IE. :)

In addition to querySelectorAll, we can use querySelector which returns only the first descendant element. Also, querySelector is not restricted to CSS IDs and Classes – you can use this with HTML5 elements as well:

document.querySelector(‘footer’);

Um…What About Browser Support?

QuerySelector and querySelectorAll are supported by all the major browsers from IE8 and up. Of course you need to be careful which CSS selectors you are querying because not all browser versions recognize all selectors.

Should I care?

Poke around inside jQuery and you’ll find references to querySelector – looks like jQuery is using this native API too (when it can). So, if you’re already using jQuery in your project and you’re more comfortable with jQuery selectors this new API isn’t going to rock your world. If you’re not using jQuery, are not worried about old pre-IE8 browsers and are trying to keep your project super-lightweight then these new selectors will make your coding much easier. So it looks like it is up to you and your situation.

Want to Improve your JavaScript Chops?

ngietka (4 Posts)

Noah joined the RE team directly after receiving his BA degree in Web Design. Noah is a creative web developer with a strong technological foundation and a genuine zeal for design and front-end development. He is an Adobe Certified Expert who has never tested for MENSA but feels he would probably get in easily.


* Required


Comments

  1. Peter Galiba 10 April 2012 at 10:49 pm permalink

    You didn’t write the solution about toggling a class, although recent browsers has the classList property, with which you can go through all the classes an element has, add new, remove and toggle them.