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
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
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.
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.