Book Image

Instant jQuery Selectors

By : Aurelio De Rosa
Book Image

Instant jQuery Selectors

By: Aurelio De Rosa

Overview of this book

jQuery's selectors is one of the most important concepts of the jQuery library. Usually, the first thing you do is to select one or more elements of a page in order to manipulate them. Therefore, to efficiently learn the usage of jQuery's selectors is one of the first steps to successfully build your website. Instant jQuery Selectors is a practical guide that will teach you how to use jQuery's selectors efficiently in order to easily select theelements of your pages to operate upon with jQuery's methods. You will go through the most common problems that you could face while developing your project and will learn how to solve them with the help of focused examples that Instant jQuery Selectors has to offer. Instant jQuery Selectors, starting from how to set up jQuery and how to choose the right version for your project, explains to you all the selectors available using a multitude of simple and practical recipes that will help you start using selectors in the right way. Reading the presented recipes you'll learn about the numerous selectors and filters of jQuery – almost 100 of them! You will see how to reuse collections, the methods to filter collections, and how to take advantage of the lesser known parameter of jQuery's constructor: context. Also, you'll discover the methods to traverse the DOM and the techniques to improve the performance of your website by just tweaking selectors. Instant jQuery Selectors is the resource to learn everything you need to know about jQuery's selectors.
Table of Contents (7 chapters)

Selecting by class (Must know)


In this recipe we'll see how to select a collection of elements using the Class selector. Our goal is to hide all of the elements having the class red.

How to do it...

To achieve the prefixed objective, we need to perform the following steps:

  1. Create a copy of the template.html file and rename it as selecting-by-class.html.

  2. Inside the <body> tag, add the following HTML markup:

    <h1 id="title" class="bold red">The Class selector</h1>
    <div id="container">
        This example shows you how to use the Class selector.
        <p id="description" class="red">After you'll click the button below, the h1 and this p will be hidden.</p>
        <p id="note" class="green">This happens because of their class attribute's value.</p>
    </div>
    <button id="hide-button">Hide elements!</button>
  3. Edit the <head> section of the page adding this code:

    <script>
        $(document).ready(function() {
            $('#hide-button').click(function() {
                $('.red').hide();
            });
        });
    </script>
  4. Save the file and open it with your favorite browser.

How it works...

First of all, we need to write some markup to fill the web page. Most of the added elements have a class attribute defined with some hypothetical values. Those classes don't actually change the style because we haven't defined them. One of the tags written is a button that we'll use to attach a handler.

Inside our usual anonymous function, attached to the document's ready event, we put our logic. Using the knowledge gained so far, we select the button by its ID (hide button), and then attach another anonymous function that will be fired as soon as a click event occurs. In general, this event is triggered when the mouse is over an element, and then the mouse button is pressed and released. In our case, we're listening when this happens to the button. Inside the inner handler, we have just one statement.

Using the CSS conventions, we're prepending a dot before the chosen class name, red. So, we're passing the string to the jQuery constructor to select all of the elements having class red. The framework won't choose only the nodes having red as unique value of the class attribute (for example, class="red"), but also those having multiple classes where one of them is red (for example, class="bold red"). Giving the HTML code written, the selected elements are the h1 and the first p.

Once we have retrieved the collection, we pass it to the library's hide() method. As the name suggests, it hides the matched elements. It's highly configurable, but for the sake of our example, we used its most basic form that hides elements immediately, without animation.

There's more...

Several browsers have a native function to select elements by their class name. Let's see what jQuery does behind the scenes.

getElementsByClassName()

Where possible, jQuery uses the getElementsByClassName() function to select elements using their class name. The browsers where this function is applied are IE9+, Firefox 3+, Chrome, Safari, and Opera 9.5+. Being native, its performances are quite good, although not comparable to those of getElementById().

Note

Versions of Internet Explorer prior to 9 don't have a native function to select elements by a class, so with a considerable amount of elements in the DOM, the performance can be very bad. However, for projects that aren't targeting IE6 to 8 users, or are using jQuery 2.X, this note can be ignored.

In case you need to take care of performances for Internet Explorer 6 to 8, here is a tip for you.

Due to the lack of getElementsByClassName() in IE6 to 8 you can optimize the search by class name, if it's applied to elements with the same tag name, prepending the latter to the class name itself. For example, if you want to select all of the p having class red, instead of using $('.red'), you can write $('p.red').

Selecting elements having two or more classes

In the last example, we've seen how to select elements having red as class, but you can do more than that. You can also select elements having a class and another one. For example, suppose we want to select an element with both red and bold class. To achieve this goal, you need to simply concatenate class selectors, as follows:

$('.red.bold').hide();