Since the ubiquitous of jQuery's usage, many of you may not know there are some built in CSS selector APIs in javascipt core.

The are querySelector and querySelectorAll. When you don't have jQuery support, you can use them .

Both of them accept same syntax of selector parameter except querySelector return the first element matached, and querySelectoirAll return all of them as a NodeList ( not an array ).

Lets select element by its id.

 
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US" xmlns:og="http://ogp.me/ns#">
  <head profile="http://gmpg.org/xfn/11">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title></title>
 
  </head>
  <style>
 
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, input, menu, nav, output, ruby, section, summary, time, mark, audio, video {
border: 0;
margin: 0;
padding: 0;
vertical-align: baseline;
}
 
</style>
  <body>
  <div id="headerbar">
    <div class="inner">
      <a href="http://google.com/" id="google">Google</a>
      <a href="http://yahoo.com/" id="yahoo">Yahoo</a>
    </div>
  </div>
  </div>
  </body>
</html>
<script>
(function () {
    var headElement = document.querySelector('#headerbar');
    alert(headElement.tagName);
 
})();
</script>
 

Here, the document is called base element, querySelector will search in all descendents of the base element. For example we can search in headElement only.

 
    var inner = headElement.querySelector('#google');
    alert( 'href is ' + inner.href);
 

Search elements by attribute.

 
    var byAttr = document.querySelector("a[id='google']");
    alert( 'href is ' + byAttr.href);
 

Search them all.

 
    var links = document.querySelectorAll('#headerbar .inner a');
    alert(links.length);
 
    for ( var i = 0 ; i < links.length ;  i++ ) {
        alert(links[i].href);
    }
 

How many browsers support this API?

Almost all modern browsers support this feature. Only a few old browsers don't support it, they are IE less than IE 8.0 ( not include IE 8), firefox less than 3.0 , Opera lessthan 10.0.

Its quite safe to use them without worries.