Saturday, January 25, 2025

Working with HTML5 selector API

10/20/13

 

Introduction

Prior to HTML5, the support for querying elements of a web page was very restrictive. This resulted in  web developers having to write targeted code to retrieve Element nodes from the Document Object Model (DOM) by passing node identifiers like ID, ClassName, Name, TagName and namespace.

The APIs used in pre-HTML days were:

·         document.getElementById

·         document.getElementsByClassName

·         document.getElementsByName

·         document.getElementsByTagName

·         document.getElementsbyTagNameNS

 

Let us explore the document.getElementbyId in more detail. This API can be used to get a handle to an element by passing in an element ID.  This would not work on a group of elements with the same ID, since the handle would be point to a single element only.

To make it better, the HTML5 specification introduced new selector APIs that allowed better queries.

 

The HTML5 specification says….

To quote the specification,

The HTML5 specification provides methods for selecting and testing elements based on whether or not they match a given selector. With these methods, it is easier to match a set of Element nodes based on specific criteria, than having to subsequently filter the result of calling other methods like getElementsByTagName().

The interface definition of these APIs is

partial interface Document {

  Element?  querySelector(DOMString selectors);

  NodeList  querySelectorAll(DOMString selectors);

};

 

partial interface DocumentFragment {

  Element?  querySelector(DOMString selectors);

  NodeList  querySelectorAll(DOMString selectors);

};

 

partial interface Element {

  Element?  querySelector(DOMString selectors);

  NodeList  querySelectorAll(DOMString selectors);

};

 

 

This implies that “document  now supports querying by a selector string and returning one element (via document.querySelector) or multiple elements (via document.querySelectorAll)

 

The document.querySelector API returns the first element which matches the specified DOM string, whereas document.querySelectorAll API returns all the elements which match the specified DOM string.

 

Hands On

Let us write a simple HTML5 web page which demonstrates how to use the selector APIs.

For this demo, we will create a simple web page and create a unordered list. We will associate each row of the list with a class, either “odd” or “even”.  We will use selector APIs to access the rows and control how they look.

Our list is defined as

<ul id=”dataList“>

              <li class=”odd”>Odd 1</li>

              <li class=”even”>Even 1</li>

              <li class=”odd”>Odd 2</li>

              <li class=”even”>Even 2</li>

              <li class=”odd”>Odd 3</li>

       </ul>     

 

To access the first row in the datalist belonging to odd class, we will call the selector API document.querySelector() and pass it the argument that identifies the odd row, in our case it is will be “li.odd”.

To get the first even row, our query selector will be “li.even” and we will call document.querySelector API.

To get all the rows which match the query selector, we will call document.querySelectorAll API.

Now, let us build a complete web page which shows this in action. The code snippet is listed below.

 

<!DOCTYPE html>

<html>

<meta charset=”utf-8″>

<title>Selector sample</title>

<body>

<button id=”buttonSelectFirstOddRow type=”button” onclick=”buttonSelectFirstOddRow_click()“>Select First Odd Row</button>

<button id=”buttonSelectFirstEvenRow type=”button” onclick=”buttonSelectFirstEvenRow_click()“>Select First Even Row</button>

<button id=”buttonSelectAllOddRows type=”button” onclick=”buttonSelectAllOddRows_click()“>Select All Odd Row</button>

<button id=”buttonSelectAllEvenRows type=”button” onclick=”buttonSelectAllEvenRows_click()“>Select All Even Row</button>

<button id=”buttonSelectAllRows type=”button” onclick=”buttonSelectAllRows_click()“>Select All Rows</button>

    <article>

        <header>

            <h1>Selector API sample</h1>

            <p>Demo showing how to use HTML5 selector API</p>

        </header>

       <ul id=”dataList“>

              <li class=”odd”>Odd 1</li>

              <li class=”even”>Even 1</li>

              <li class=”odd”>Odd 2</li>

              <li class=”even”>Even 2</li>

              <li class=”odd”>Odd 3</li>

       </ul>     

        <footer>

            <h1></h1>

            <p>HTML Goodies</p>

        </footer>

    </article>

    <script type=”text/javascript“>

       function buttonSelectFirstOddRow_click()

       {

     

              var selectedRow = document.querySelector(li.odd);

              selectedRow.style.color = ‘Red’;

       }

       function buttonSelectFirstEvenRow_click()

       {

              var selectedRow = document.querySelector(li.even);

              selectedRow.style.color = ‘Green’;

       }

       function buttonSelectAllOddRows_click()

       {

              var selectedRows = document.querySelectorAll(li.odd);

              for (var i = 0; i < selectedRows.length; i++)

                     selectedRows[i].style.color = ‘Red’;

       }

       function buttonSelectAllEvenRows_click()

       {

              var selectedRows = document.querySelectorAll(li.even);

              for (var i = 0; i < selectedRows.length; i++)

                     selectedRows[i].style.color = ‘Green’;

       }

       function buttonSelectAllRows_click()

       {

              var selectedRows = document.querySelectorAll(li.odd, li.even);

              for (var i = 0; i < selectedRows.length; i++)

                     selectedRows[i].style.color = ‘Pink’;

       }

    </script>

</body>

</html>

 

The above code snippet is also available as a download from here.

When you run this webpage in the latest version of your browser (IE, Firefox and Chrome), you can see the selector API in action  by clicking on the buttons and seeing the rows change color.

 

Summary

In this article, we learned about the HTMl5 selector APIs. I hope you have found this article useful.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured