Click here to Skip to main content
Click here to Skip to main content

Tagged as

HTML5 – Selectors API Level 1

, 22 Jul 2011
Rate this:
Please Sign up or sign in to vote.
HTML5 – Selectors API Level 1Lately, I’m dealing a lot with HTML5. I co-authored a three days course in that topic for Sela, the 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 th

Lately, I’m dealing a lot with HTML5. I co-authored a three days 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 is 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 make 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 give 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 got familiar with the specifications lets deep dive into an example. In the example I’m going to use the following HTML fragment:

<!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:

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:

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:

<!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: 

<!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 depends 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 uses under the hood 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)

Share

About the Author

Gil Fink
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
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web03 | 2.8.140827.1 | Last Updated 22 Jul 2011
Article Copyright 2011 by Gil Fink
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid