Click here to Skip to main content
15,884,425 members
Articles / Web Development / HTML5

HTML5 – Selectors API Level 1

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
22 Jul 2011CPOL3 min read 11.3K   1  
HTML5 – Selectors API Level 1

Lately, I’m dealing a lot with HTML5. I co-authored a three day course in that topic for Sela, HTML5 – Selectors API Level 1the company I work for. During the process of creating the course, I got to learn a lot about HTML5 and what to expect from the new specifications, so expect more posts about this subject in the near future. In this post, I’m going to describe what are the JavaScript Selectors API Level 1 and compare it with jQuery.

Selectors API

The Selectors API enables web developers to select DOM elements and retrieve DOM nodes that match against a group of selectors. This approach simplifies the selection of elements and makes it integrated directly in the browser. The API describes two new and powerful methods that enable selections:

  • querySelector – Selects the first match for a given selection expression and returns a DOM element
  • querySelectorAll – Selects all the matches for a given selection expression and returns DOM elements array

The selection expression is a CSS3 group of selectors that can be separated with commas (which means Logical Or between the selected elements).

For further reading about the Selectors API, go to the specifications.

Selecting Elements using Selectors API

Now that we have become familiar with the specifications, let's deep dive into an example. In the example, I’m going to use the following HTML fragment:

HTML
<!DOCTYPE html>
<html>
<head>
    <title>Selectors Example</title>
    <style type="text/css">
        .red
        {
            color: Red;
        }
        .blue
        {
            color: Blue;
        }
    </style>
</head>
<body>
    <ul id="ulOfItems">
        <li>item 1</li>
        <li class="red">item 2</li>
        <li id="item3">item 3</li>
        <li class="red">item 4</li>
        <li>item 5</li>
    </ul>
</body>
</html>

When I want to use the Selectors API in order to grab the first list item with red class, I’ll write the following line of code:

JavaScript
var elm = document.querySelector("ul li.red");

If I want to grab all the list items with red class, I’ll write the following line of code:

JavaScript
var elements = document.querySelectorAll("ul li.red");

Here is a full example with two methods that select the single or multiple list items and then change their class name when a button is clicked:

HTML
<!DOCTYPE html>
<html>

<head>
    <title>Selectors Example</title>

    <style type="text/css">
        .red

        {
            color: Red;

        }
        .blue

        {
            color: Blue;

        }
    </style>    

</head>
<body>

    <ul id="ulOfItems">
        <li>item 1</li>

        <li class="red">item 2</li>
        <li id="item3">item 3</li>

        <li class="red">item 4</li>
        <li>item 5</li>

    </ul>
    <input type="button" name="btnFirstElm" 
        value="Change First Element Class Name" 
        onclick="changeClassNameToBlueToFirstLI()"/>

    <input type="button" name="btnAllElm" 
        value="Change All Elements Class Name" onclick="changeClassNameToBlueToAllLI()"/>
    <script type="text/javascript">

        function changeClassNameToBlueToFirstLI() {
            var elm = document.querySelector("ul li.red");

            elm.className = "blue";
        }
 
        function changeClassNameToBlueToAllLI() {

            var elements = document.querySelectorAll("ul li.red");
            for (var i = 0; i < elements.length; i++) {

                elements[i].className = "blue";
            }
        }        
    </script>

</body>
</html>

Comparing Selectors API To jQuery Selectors

When I first heard about Selectors API, you could probably hear me grin. jQuery and other JavaScript libraries are doing the same thing for years. The only difference between an external library and native support in the browser in this case is that you need to download the external library in all the pages they are needed. This can be minimized with the use of CDNs or client cache for better performance. So what gives native browser support gives those libraries the ability to use and implement a better selection implementation. If you’ll open jQuery 1.6.2 (the latest version) and seek for the word querySelector, you’ll see that jQuery is targeting the new selection functions first by applying feature detection. So under the hood, jQuery will use the native selection support, if available in the browser, and that is perfect. So how will you refactor the previous example to use jQuery?

Here is a proposed implementation:

HTML
<!DOCTYPE html>
<html>

<head>
    <title>Selectors Example</title>

    <script src="jquery-1.6.2.js" type="text/javascript"></script>
    <style type="text/css">

        .red
        {

            color: Red;
        }

        .blue
        {

            color: Blue;
        }

    </style>
</head>

<body>
    <ul id="ulOfItems">

        <li>item 1</li>
        <li class="red">item 2</li>

        <li id="item3">item 3</li>
        <li class="red">item 4</li>

        <li>item 5</li>
    </ul>

    <input type="button" id="btnFirstElm" value="Change First Element Class Name" />
    <input type="button" id="btnAllElm" value="Change All Elements Class Name" />

    <script type="text/javascript">
        $(document).ready(function () {

            $('#btnFirstElm').click(function () {
                $('ul li.red').first().toggleClass('blue');

            }); 

            $('#btnAllElm').click(function () {
                $('ul li.red').each(function () {

                    $(this).toggleClass('blue');
                });

            });
        });

    </script>
</body>

</html>

Even though the adding of better native browser support for selection is a great thing, still jQuery and other JavaScript libraries offer more richness and more selection options. Since these external libraries depend upon native browser API, then underneath they might be using the Selectors API and as I wrote, jQuery is doing exactly that.

Summary

The post explained what are the new HTML5 Selectors API functions. It also compared the new API to the use of selectors in jQuery. The bottom line is that you might use the new API and gain native browser support for selectors or you might use jQuery (or other JavaScript libraries) that under the hood uses the same functions if they are available. The choice is yours.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead sparXys
Israel Israel
Gil Fink is a web development expert and ASP.Net/IIS Microsoft MVP. He is the founder and owner of sparXys. He is currently consulting for various enterprises and companies, where he helps to develop Web and RIA-based solutions. He conducts lectures and workshops for individuals and enterprises who want to specialize in infrastructure and web development. He is also co-author of several Microsoft Official Courses (MOCs) and training kits, co-author of "Pro Single Page Application Development" book (Apress) and the founder of Front-End.IL Meetup. You can read his publications at his website: http://www.gilfink.net

Comments and Discussions

 
-- There are no messages in this forum --