Over a million developers have joined DZone.

HTML5 – Selectors API Level 1

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

Lately, 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 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.

 

Source: http://blogs.microsoft.co.il/blogs/gilf/archive/2011/07/12/html5-selectors-api-level-1.aspx

 

 

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}