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
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Learning jQuery - Fourth Edition
Learning jQuery - Fourth Edition

Learning jQuery - Fourth Edition: Add to your current website development skills with this brilliant guide to JQuery. This step by step course needs little prior JavaScript knowledge so is suitable for beginners and more seasoned developers alike. , Fourth Edition

eBook
£17.99 £25.99
Paperback
£32.99
Subscription
Free Trial
Renews at £16.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Learning jQuery - Fourth Edition

Chapter 2. Selecting Elements

The jQuery library harnesses the power of Cascading Style Sheets (CSS) selectors to let us quickly and easily access elements or groups of elements in Document Object Model (DOM).

In this chapter, we will cover:

  • The structure of the elements on a web page

  • How to use CSS selectors to find elements on the page

  • Custom jQuery extensions to the standard set of CSS selectors

  • The DOM traversal methods, which provide greater flexibility for accessing elements on the page

Understanding the DOM


One of the most powerful aspects of jQuery is its ability to make selecting elements in the DOM easy. The DOM serves as the interface between JavaScript and a web page; it provides a representation of the source HTML as a network of objects rather than as plain text.

This network takes the form of a family tree of elements on the page. When we refer to the relationships that elements have with one another, we use the same terminology that we use when referring to family relationships: parents, children, and so on. A simple example can help us understand how the family tree metaphor applies to a document:

<html>
  <head>
    <title>the title</title>
  </head>
  <body>
    <div>
      <p>This is a paragraph.</p>
      <p>This is another paragraph.</p>
      <p>This is yet another paragraph.</p>
    </div>
  </body>
</html>

Here, <html> is the ancestor of all the other elements...

Using the $() function


The resulting set of elements from jQuery's selectors and methods is always represented by a jQuery object. Such a jQuery object is very easy to work with when we want to actually do something with the things that we find on a page. We can easily bind events to these objects and add slick effects to them, as well as chain multiple modifications or effects together.

Note

Note that jQuery objects are different from regular DOM elements or node lists, and as such do not necessarily provide the same methods and properties for some tasks. In the final part of this chapter, we will look at ways to directly access the DOM elements that are collected within a jQuery object.

In order to create a new jQuery object, we use the $() function. This function typically accepts a CSS selector as its sole parameter and serves as a factory returning a new jQuery object pointing to the corresponding elements on the page. Just about anything that can be used in a stylesheet can also be passed...

CSS selectors


The jQuery library supports nearly all the selectors included in CSS specifications 1 through 3, as outlined on the World Wide Web Consortium's site: http://www.w3.org/Style/CSS/specs. This support allows developers to enhance their websites without worrying about which browsers might not understand more advanced selectors, as long as the browsers have JavaScript enabled.

Tip

Progressive Enhancement

Responsible jQuery developers should always apply the concepts of progressive enhancement and graceful degradation to their code, ensuring that a page will render as accurately, even if not as beautifully, with JavaScript disabled as it does with JavaScript turned on. We will continue to explore these concepts throughout the book. More information on progressive enhancement can be found at http://en.wikipedia.org/wiki/Progressive_enhancement.

To begin learning how jQuery works with CSS selectors, we'll use a structure that appears on many websites, often for navigation – the nested...

Attribute selectors


Attribute selectors are a particularly helpful subset of CSS selectors. They allow us to specify an element by one of its HTML attributes, such as a link's title attribute or an image's alt attribute. For example, to select all images that have an alt attribute, we write the following:

$('img[alt]')

Styling links

Attribute selectors accept a wildcard syntax inspired by regular expressions for identifying the value at the beginning (^) or end ($) of a string. They can also take an asterisk (*) to indicate the value at an arbitrary position within a string or an exclamation mark (!) to indicate a negated value.

Let's say we want to have different styles for different types of links. We first define the styles in our stylesheet:

a {
  color: #00c; 
}
a.mailto {
  background: url(images/email.png) no-repeat right top;
  padding-right: 18px;
}
a.pdflink {
  background: url(images/pdf.png) no-repeat right top;
  padding-right: 18px;
}
a.henrylink {
  background-color: #fff;
  padding...

Custom selectors


To the wide variety of CSS selectors, jQuery adds its own custom selectors. These custom selectors enhance the already impressive capabilities of CSS selectors to locate page elements in new ways.

Tip

Performance note

When possible, jQuery uses the native DOM selector engine of the browser to find elements. This extremely fast approach is not possible when custom jQuery selectors are used. For this reason, it is recommended to avoid frequent use of custom selectors when a native option is available and performance is very important.

Most of the custom selectors allow us to choose one or more elements from a collection of elements that we have already found. The custom selector syntax is the same as the CSS pseudo-class syntax, where the selector starts with a colon (:). For example, to select the second item from a set of <div> elements with a class of horizontal, we write this:

$('div.horizontal:eq(1)')

Note that :eq(1) selects the second item in the set because JavaScript...

DOM traversal methods


The jQuery selectors that we have explored so far allow us to select a set of elements as we navigate across and down the DOM tree and filter the results. If this were the only way to select elements, our options would be somewhat limited. There are many occasions when selecting a parent or ancestor element is essential; that is where jQuery's DOM traversal methods come into play. With these methods at our disposal, we can go up, down, and all around the DOM tree with ease.

Some of the methods have a nearly identical counterpart among the selector expressions. For example, the line we first used to add the alt class, $('tr:even').addClass('alt'), could be rewritten with the .filter() method as follows:

$('tr').filter(':even').addClass('alt');

For the most part, however, the two ways of selecting elements complement each other. Also, the .filter() method in particular has enormous power because it can take a function as its argument. The function allows us to create complex...

Accessing DOM elements


Every selector expression and most jQuery methods return a jQuery object. This is almost always what we want because of the implicit iteration and chaining capabilities that it affords.

Still, there may be points in our code when we need to access a DOM element directly. For example, we may need to make a resulting set of elements available to another JavaScript library, or we might need to access an element's tag name, which is available as a property of the DOM element. For these admittedly rare situations, jQuery provides the .get() method. To access the first DOM element referred to by a jQuery object, for example, we would use .get(0). So, if we want to know the tag name of an element with an ID of my-element, we would write:

varmyTag = $('#my-element').get(0).tagName;

For even greater convenience, jQuery provides a shorthand for .get(). Instead of writing the previous line, we can use square brackets immediately following the selector:

varmyTag = $('#my-element'...

Summary


With the techniques that we have covered in this chapter, we should now be able to locate sets of elements on the page in a variety of ways. In particular, we learned how to style top-level and sub-level items in a nested list by using basic CSS selectors, how to apply different styles to different types of links by using attribute selectors, add rudimentary striping to a table by using either the custom jQuery selectors :odd and :even or the advanced CSS selector :nth-child(), and highlight text within certain table cells by chaining jQuery methods.

So far, we have been using the $(document).ready() method to add a class to a matched set of elements. In the next chapter, we'll explore ways in which to add a class in response to a variety of user-initiated events.

Further reading

The topic of selectors and traversal methods will be explored in more detail in Chapter 9, Advanced Selectors and Traversing. A complete list of jQuery's selectors and traversal methods is available in Appendix...

Exercises


To complete these exercises, you will need the index.html file for this chapter, as well as the finished JavaScript code as found in complete.js. These files can be downloaded from the Packt Publishing web site at http://www.packtpub.com/support.

Challenge exercises may require the use of the official jQuery documentation at http://api.jquery.com/:

  1. Add a class of special to all of the <li> elements at the second level of the nested list.

  2. Add a class of year to all the table cells in the third column of a table.

  3. Add the class special to the first table row that has the word Tragedy in it.

  4. Challenge: Select all the list items (<li>s) containing a link (<a>). Add the class afterlink to the sibling list items that follow the ones selected.

  5. Challenge: Add the class tragedy to the closest ancestor <ul> of any .pdf link.

Left arrow icon Right arrow icon

Key benefits

  • An introduction to jQuery that requires minimal programming experience
  • Detailed solutions to specific client-side problems
  • Revised and updated version of this popular jQuery book

Description

To build interesting, interactive sites, developers are turning to JavaScript libraries such as jQuery to automate common tasks and simplify complicated ones. Because many web developers have more experience with HTML and CSS than with JavaScript, the library's design lends itself to a quick start for designers with little programming experience. Experienced programmers will also be aided by its conceptual consistency. LearningjQuery - Fourth Edition is revised and updated version of jQuery. You will learn the basics of jQuery for adding interactions and animations to your pages. Even if previous attempts at writing JavaScript have left you baffled, this book will guide you past the pitfalls associated with AJAX, events, effects, and advanced JavaScript language features. Starting with an introduction to jQuery, you will first be shown how to write a functioning jQuery program in just three lines of code. Learn how to add impact to your actions through a set of simple visual effects and to create, copy, reassemble, and embellish content using jQuery's DOM modification methods. The book will take you through many detailed, real-world examples, and even equip you to extend the jQuery library itself with your own plug-ins.

Who is this book for?

This book is for web designers who want learn jQuery to create interactive elements for their designs, as well as developers who want to create the best user interface for their web applications. Basic JavaScript programming and knowledge of HTML and CSS is required. No knowledge of jQuery is assumed, nor is experience with any other JavaScript libraries.

What you will learn

  • Create interactive elements for your web designs
  • Learn how to create the best user interface for your web applications
  • Use selectors in a variety of ways to get anything you want from a page
  • Make things happen on your webpages with events
  • Add flair to your actions with a variety of animation effects
  • Discover the new features available in jQuery in this third update of this popular jQuery book

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jun 25, 2013
Length: 444 pages
Edition : 4th
Language : English
ISBN-13 : 9781782163152
Languages :
Concepts :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Jun 25, 2013
Length: 444 pages
Edition : 4th
Language : English
ISBN-13 : 9781782163152
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
£16.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
£169.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just £5 each
Feature tick icon Exclusive print discounts
£234.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just £5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total £ 107.97
Object-Oriented JavaScript - Second Edition
£41.99
Learning jQuery - Fourth Edition
£32.99
Responsive Web Design with HTML5 and CSS3
£32.99
Total £ 107.97 Stars icon

Table of Contents

13 Chapters
Getting Started Chevron down icon Chevron up icon
Selecting Elements Chevron down icon Chevron up icon
Handling Events Chevron down icon Chevron up icon
Styling and Animating Chevron down icon Chevron up icon
Manipulating the DOM Chevron down icon Chevron up icon
Sending Data with Ajax Chevron down icon Chevron up icon
Using Plugins Chevron down icon Chevron up icon
Developing Plugins Chevron down icon Chevron up icon
Advanced Selectors and Traversing Chevron down icon Chevron up icon
Advanced Events Chevron down icon Chevron up icon
Advanced Effects Chevron down icon Chevron up icon
Advanced DOM Manipulation Chevron down icon Chevron up icon
Advanced Ajax Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.2
(20 Ratings)
5 star 60%
4 star 15%
3 star 5%
2 star 20%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Klen Aug 23, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I have the third edition and bought this fourth one to refresh my skills (I do JavaScript programming very often these days). The book was great when I started serious programming (with 3rd edition) and it's great now. Recommended!
Amazon Verified review Amazon
Alex Babushka Jul 11, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Learning jQuery is an outstanding book written by the masters and accessible to anyone with at least a basic understanding of JavaScript. The authors take a truly comprehensive approach to the subject, providing in-depth explanations of the library's fundamentals as well as more advanced features and packing the book with useful code examples.Now in its fourth edition, this text has finally received a much needed update covering the latest versions of jQuery 1.10 and 2.0. An entire chapter is dedicated to building plugins - just what I needed! Also, two (newly refreshed) chapters each on event handling, effects and Ajax methods leave virtually no stone unturned.If you are just starting out with jQuery, don't waste your time reading a For Dummies book; instead, pick up a copy of this 400 page bad boy (or a digital edition available directly from Packt Publishing) and it'll be the only book you'll need to read.
Amazon Verified review Amazon
AddictedShopper Dec 25, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is the best jQuery book out there. It's clear and comprehensive. You do need to know a little HTML and Javascript to follow along. All of the code examples worked except for that code example 9 from chapter 9(advance selector, group filter). In order to get the code examples, I think you need an account on the publisher's website. Overall, the book is very good.Update: the code is now available at book.learningjquery.com so you don't have to go through packt. I upped the rating from 4 to 5 stars
Amazon Verified review Amazon
James M. Johnson III Mar 26, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great book, if a little dry.
Amazon Verified review Amazon
AU Aug 13, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I care about details and this book gives me all of it. It even gives you a little review of JavaScript.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.