Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
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 : Better Interaction Design and Web Development with Simple JavaScript Techniques
Learning  jQuery : Better Interaction Design and Web Development with Simple JavaScript Techniques

Learning jQuery : Better Interaction Design and Web Development with Simple JavaScript Techniques: Better Interaction Design and Web Development with Simple JavaScript Techniques

€22.99 €25.99
eBook Jul 2007 380 pages Edition
eBook
€22.99 €25.99
Subscription
Free Trial
Renews at €18.99p/m
€22.99 €25.99
eBook Jul 2007 380 pages Edition
eBook
€22.99 €25.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€22.99 €25.99
Subscription
Free Trial
Renews at €18.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 : Better Interaction Design and Web Development with Simple JavaScript Techniques

Chapter 2. Selectors—How to Get Anything You Want

 

She’s just the girl

She’s just the girl

The girl you want

 
 -- Devo, “Girl U Want”

jQuery harnesses the power of Cascading Style Sheets (CSS) and XPath selectors to let us quickly and easily access elements or groups of elements in the Document Object Model (DOM). In this chapter, we will explore a few of these CSS and XPath selectors, as well as jQuery’s own custom selectors. We’ll also look at jQuery’s DOM traversal methods that provide even greater flexibility for getting what we want.

The Document Object Model

One of the most powerful aspects of jQuery is its ability to make DOM traversal easy. The Document Object Model is a family-tree structure of sorts. HTML, like other markup languages, uses this model to describe the relationships of things on a page. When we refer to these relationships, we use the same terminology that we use when referring to family relationships—parents, children, and so on. A simple example can help us...

The Document Object Model


One of the most powerful aspects of jQuery is its ability to make DOM traversal easy. The Document Object Model is a family-tree structure of sorts. HTML, like other markup languages, uses this model to describe the relationships of things on a page. When we refer to these relationships, 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; in other words, all the other elements are descendants of <html>. The <head> and <body>...

The $() Factory Function


No matter which type of selector we want to use in jQuery—be it CSS, XPath, or custom—we always start with the dollar sign and parentheses: $()

As mentioned in Chapter 1, the $() function removes the need to do a for loop to access a group of elements since whatever we put inside the parentheses will be looped through automatically and stored as a jQuery object. We can put just about anything inside the parentheses of the $() function. A few of the more common examples include:

  • A tag name: $('p') gets all paragraphs in the document.

  • An ID: $('#some-id') gets the single element in the document that has the corresponding some-id ID.

  • A class: $('.some-class') gets all elements in the document that have a class of some-class.

Note

Making jQuery Play Well with Other JavaScript Libraries

In jQuery, the dollar sign $ is simply shorthand for jQuery. Because a $() function is very common in JavaScript libraries, conflicts could arise if more than one of these libraries...

CSS Selectors


jQuery supports most of 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 (particularly Internet Explorer 6 and below) might not understand advanced selectors, as long as the browsers have JavaScript enabled.

Note

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.

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

<ul id="selected-plays">
  <li>Comedies
    <ul>
      <li><a href="http...

XPath Selectors


XML Path Language (XPath) is a type of language for identifying different elements or their values within XML documents, similar to the way CSS identifies elements in HTML documents. The jQuery library supports a basic set of XPath selectors that we can use alongside CSS selectors, if we so desire. And with jQuery, both XPath and CSS selectors can be used regardless of the document type.

When it comes to attribute selectors, jQuery uses the XPath convention of identifying attributes by prefixing them with the @ symbol inside square brackets, rather than the less-flexible CSS equivalent. For example, to select all links that have a title attribute, we would write the following:

$('a[@title]')

This XPath syntax allows for another use of square brackets, without the @, to designate an element that is contained within another element. We can, for example, get all div elements that contain an ol element with the following selector expression:

$('div[ol]')

Styling Links

Attribute selectors...

Custom Selectors


To the wide variety of CSS and XPath selectors, jQuery adds its own custom selectors. Most of the custom selectors allow us to pick certain elements out of a line-up, so to speak. The syntax is the same as the CSS pseudo-class syntax, where the selector starts with a colon (:). For example, if we wanted to select the second item from a matched set of divs with a class of horizontal, we would write it like this:

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

Note that the eq(1) gets the second item from the set because JavaScript array numbering is zero-based, meaning that it starts with 0. In contrast, CSS is one-based, so a CSS selector such as $('div:nth-child(1)') gets any div that is the first child of its parent.

Styling Alternate Rows

Two very useful custom selectors in the jQuery library are :odd and :even. Let’s take a look at how we can use these selectors for basic table striping, given the following table:

<table>
<tr>
  <td>As You Like It</td>
  <td>Comedy...

DOM Traversal Methods


The jQuery selectors that we have explored so far allow us to get a set of elements as we navigate across and down the DOM tree and filter the results. If this were the only way to get elements, our options would be quite limited (although, frankly, the selector expressions on their own are robust in their own right, especially when compared to the regular DOM scripting). There are many occasions on which getting a parent or ancestor element is essential. And that is where jQuery’s DOM traversal methods come to 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 used to add the odd class, $('tr:odd'). addClass('odd');, could be rewritten with the .filter() method as follows:

$('tr').filter(':odd').addClass('odd');

For the most part, however, the two ways of getting elements complement each other. Let’s take a...

Accessing DOM Elements


Every selector expression and most jQuery methods return a jQuery object, which 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. For these admittedly rare situations, jQuery provides the .get() method. To access the first DOM element referred to by a jQuery object, we would use .get(0). If the DOM element is needed within a loop, we would use .get(index). So, if we want to know the tag name of an element with id="my-element", we would write:

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

For even greater convenience, jQuery provides a shorthand for .get(). Instead of writing $('#my-element').get(0), for example, we can use square brackets immediately following the selector: ...

Summary


With the techniques that we have covered in this chapter, we should now be able to style top-level and sub-level items in a nested list by using CSS selectors, apply different styles to different types of links by using XPath attribute selectors, add rudimentary striping to a table by using the custom jQuery selectors :odd and :even, and highlight text within certain table cells by chaining jQuery methods.

So far, we have been using the $(document).ready() event 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.

Left arrow icon Right arrow icon

What you will learn

  • Use selectors to get anything you want from a page Make things happen on your page with events Add flair to your actions with animation effects Change your page on command with DOM manipulation Use AJAX to make your site buzzword compliant! Transform drab, static information containers into beautiful, dynamic tables Breathe new life into online forms Create dynamic shufflers, rotators, and galleries Get started with three official jQuery plug-ins, and even write your own

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jul 07, 2007
Length: 380 pages
Edition :
Language : English
ISBN-13 : 9781847192516
Languages :
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 : Jul 07, 2007
Length: 380 pages
Edition :
Language : English
ISBN-13 : 9781847192516
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.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
€189.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
€264.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 114.97
Building Websites with the ASP.NET Community Starter Kit
€35.99
Learning  jQuery : Better Interaction Design and Web Development with Simple JavaScript Techniques
€32.99
HTML5 Data and Services Cookbook
€45.99
Total 114.97 Stars icon

Table of Contents

10 Chapters
Getting Started Chevron down icon Chevron up icon
Selectors—How to Get Anything You Want Chevron down icon Chevron up icon
Events—How to Pull the Trigger Chevron down icon Chevron up icon
Effects—How to Add Flair to Your Actions Chevron down icon Chevron up icon
DOM Manipulation—How to Change Your Page on Command Chevron down icon Chevron up icon
AJAX—How to Make Your Site Buzzword-Compliant Chevron down icon Chevron up icon
Table Manipulation Chevron down icon Chevron up icon
Forms with Function Chevron down icon Chevron up icon
Shufflers and Rotators Chevron down icon Chevron up icon
Plug-ins Chevron down icon Chevron up icon
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.