The limitations of element selection methods in traditional JavaScript, such as getElementById
, quickly become apparent when compared to the power and flexibility of CSS selectors: getElementById('bandtable')
might get the right table, but we could have to add significantly more code to loop through and find the actual elements required by the script, such as the rows inside the table.
Adding Some Sizzle
Some of the first JavaScript frameworks directly addressed this deficit in selection power, including Sizzle, which was eventually incorporated into JQuery. Sizzle’s selective range is one of the reasons that JQuery became so popular.
JavaScript Gets A Makeover
Many developers have been using JQuery for so long that they’re not aware of changes to core JavaScript. The JavaScript Selector API is officially part of the HTML5 spec, and pretty much replaces any need for Sizzle or frameworks for element selection. One example:
document.querySelector('#eddie');
Achieves exactly the same results as document.getElementById('eddie')
. Not much advantage there, you might think. How about this?
document.querySelector('#eddie h1 + p')
That’s right. The querySelector function allows the expression of any valid combination of CSS selectors in order to find what it needs on the page.
querySelector
only matches one element: the first one it finds in the DOM. If you’re after multiple nodes, you need to use querySelectorAll
:
var hiFrets = document.querySelectorAll('table#frets tr:nth-child(3)')
This gathers a node list of every third row from any table with an id
of frets.
A Few Caveats
There are several factors that you should be aware of before making the switch to querySelector / All:
- The selection string used in querySelector must be understood by the browser natively or it will return null. This isn’t an issue unless you’re trying to use some complex CSS3 selection sequence, but it is a factor worth considering.
- Unlike
getElementsByTag
,querySelectorAll
returns a static node list gathered from the DOM as it exists at that point in time. This means that any change to the DOM tree that takes place after that point – nodes added or subtracted by JavaScript – will not be reflected in the nodelist without querySelectorAll being run again.
If you’ve been using JQuery primarily for its selection power, and can live with the conditions above, I’d recommend using querySelector
as a native method that avoids any need to load in extra frameworks and libraries.
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.