Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Instant jQuery Selectors

You're reading from   Instant jQuery Selectors Learn how to master the art of effectively using jQuery's selectors

Arrow left icon
Product type Paperback
Published in Aug 2013
Publisher Packt
ISBN-13 9781783282210
Length 70 pages
Edition 1st Edition
Tools
Arrow right icon
Author (1):
Arrow left icon
Aurelio De Rosa Aurelio De Rosa
Author Profile Icon Aurelio De Rosa
Aurelio De Rosa
Arrow right icon
View More author details
Toc

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();
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image