• home
  • forum
  • my
  • kt
  • download
  • The querySelector() and querySelectorAll() methods

    Author: 2009-03-05 08:54:25 From:

    The querySelector() and querySelectorAll() methods let you enter a CSS selector as a parameter and return the selected elements as DOM elements. Part of the W3C Selectors API, the difference between the two methods is merely in the number of possible elements that they return- the very first matched element versus the entire set. Apart from being far more versatile than the staple getElementById() and getElementsByTagName() methods, these two methods also benefit from some incredible lookup speed, as they take advantage of the same engine the browser uses to identify elements to style when parsing the CSS of a page.

    Ok, time for the obligatory reality check here- in terms of browser support, querySelector() and querySelectorAll() is supported in Firefox 3.1+, IE8+ (only in IE8 standards mode), and Safari 3.1+.

    The querySelector() method

    The querySelector() method exists both on as a Document and as an Element object. This lets you query either the entire document tree, or just a specific chunk of it looking for that elusive element of yours. It accepts any CSS selector as its parameter (ie: "#mydiv img") and returns either the first matched element (if multiple exists), or null if none. For example:

    document.querySelector('#myheader') //returns the element with ID="myheader"
    document.querySelector('p.description') //returns the P with class="description" element

    document.querySelector('#content img:nth-of-type(1)') //returns the 1st image within container "#content"
    document.querySelector('#myform input[type="radio"]:checked') //selects the checked radio button within "#myform"

    document.querySelector('#biography, #gallery') //returns either element "#biography" or "#gallery", depending on which one is found first within document tree

    Take a look at the last example above- you can enter multiple CSS selectors, each seperated by a comma (","). The comma acts like the logical OR statement here, which causes querySelector() to return the first element within the document tree that matches one of the CSS selectors entered.

    Ok, time for a quick demonstration. The below HTML creates a nested DIV, with the inner DIV changing background color whenever the mouse rolls over the outer DIV itself. It makes use of querySelector() both as a document method, and element method:

    <div id="outerdiv" style="padding:50px; width:100px; height:100px; border:1px solid black">
    <div id="innerdiv" style="width:100%; height:100%; border:1px solid black; background:silver;">
    </div>
    </div>

    <script type="text/javascript">

    if (document.querySelector){
     var outerdiv=document.querySelector('#outerdiv')
     outerdiv.onmouseover=function(){
      this.querySelector('#innerdiv').style.background="yellow"
     }
     outerdiv.onmouseout=function(){
      this.querySelector('#innerdiv').style.background="silver"
     }
    }

    </script>

    Demo (requires FF 3.1+, Safari 3.1+, or IE8+):

    The querySelectorAll() method

    The querySelectorAll() method behaves just like its more humble cousin above with the exception it returns not just a singular element that matches a CSS selector, but all of them as a staticNodeList. A staticNodeList is a static collection of elements that are not affected by any subsequent changes occuring on the document tree, such as the removal of one those elements. It supports a "length" property for you to step through each of the elements similar to in an Array. With that said:

    document.querySelectorAll('.mygroup') //returns all elements with class="mygroup"
    document.querySelectorAll('option[selected="selected"]') //returns the default selected option within each SELECT menu
    document.querySelectorAll('#mytable tr>td:nth-of-type(1)') //returns the first cell within each table row of "mytable"

    document.querySelectorAll('#biography, #gallery') //returns both elements "#biography" and "#gallery" (inclusive)

    Ok, demo time! Lets use querySelectorAll() to quickly identify all checkboxes that are selected within a particular form:

    <form id="myform">

    <b>Your hobbies:</b><input name="hobbies" type="checkbox" value="movies" />Movies <input name="hobbies" type="checkbox" value="sports" />Sports <input name="hobbies" type="checkbox" value="reading" />Reading <input name="hobbies" type="checkbox" value="sleeping" />Sleeping
    <br />
    <input type="submit" />
    </form>

    <script type="text/javascript">
    if (document.querySelector){
     document.querySelector('#myform').onsubmit=function(){
      var checkedhobbies=this.querySelectorAll('input[name="hobbies"]:checked')
      for (var i=0; i<checkedhobbies.length; i++){
       alert(checkedhobbies[i].value)
      }
      return false
     }
    }
    </script>

    Demo (requires FF 3.1+, Safari 3.1+, or IE8+):

    discuss this topic to forum

    relation tutorial

    No information

    Category

      AJAX (63)
      Content Management (12)
      Cookies (6)
      Date and Time (17)
      Development (18)
      DHTML (22)
      Forms (8)
      Frequently Asked Questions (3)
      Image Display (13)
      Introduction to Javascript (9)
      Links and Buttons (7)
      Menus (2)
      Miscellaneous (12)
      Mouse Tricks (3)
      Navigation (11)
      Randomizing (6)
      Security (5)
      Text Effects (9)
      User Authentication (2)
      User Information (5)
      Windows and Frames (6)

    New

    Hot