Tuesday, April 16, 2013

Going native JS: Select elements without jQuery - document.querySelector


Almost 7 years after jQuery's first stable release, most of the client-side development population got used to querying DOM through  jQuery (or any JavaScript framework equivalent like ExtJS) selectors. But since times are changing for web devs, how about going native? After brief research, I've came up with W3C's selector API. In short, you can select DOM elements with two methods recommended by referenced W3C papers, and implemented by most of modern browsers:

document.querySelector(selectString)

and

document.querySelectorAll(selecString)

As expected, first method will return zero or one items, while latter method will return all items selected. In terms of selectString syntax, all valid CSS selectors supported by browser, can be passed to this functions. As per browser compatibility, all modern browsers are supporting selectors API, according to caniuse, only troublemaker is IE7, that is slowly dying. 

And for the last simple demo :
(and code)

        document.querySelector('#demoButton')
           .addEventListener('click',function(){
               alert('This page has ' +
                      document.querySelectorAll('div').length + 
                      ' div elements');
       });

No comments:

Post a Comment