Chapter 3 ■ jQuery Selectors
Listing 3-1. jQuery selector to select element by id
- Windows Phone Recipes
- Visual C# 2010 Recipes
- UML Applied
- Sharepoint 2010 Designer Guide
- Pro WPF in C# 2010
- Zend Enterprise PHP Patterns
- Web Designer's Reference
- Practical Ajax Projects with Java
- The Definitive Guide to HTML5 WebSocket
- The Essential Guide to HTML5 and CSS3
How It Works
In the code, book titles are listed using
and - HTML tags. If you want to select a single node and then perform
an action on it, use the “#id” selector.
After the DOM is ready (i.e., all HTML elements are created and loaded in the browser memory), the following
code is executed as a result of the document-ready event handler.
$("#btnTestIt").click(function () {
$("#WEB-02").css("background-color", "yellow");
});
49
www.it-ebooks.info
Chapter 3 ■ jQuery Selectors
This code selects the input button with id as btnTestIt and binds a function (the event handler) to its click
event. When the user clicks this button, the following code is executed.
$("#WEB-02").css("background-color", "yellow");
$("#WEB-02") selects the HTML element - Web Designer's Reference
and returns
the jQuery object. The css() method is executed on all the HTML elements in the returned jQuery object. The first
parameter of the css() method is the style’s property name and the second parameter is the value that you want to
use to set this property. css("background-color", "yellow") changes the background color of the selected element
to yellow. css() and other DOM manipulation methods are covered in the Chapter 6. Figure 3-1 displays the page
when it is viewed in a browser.
Figure 3-1. Initial page display
When you press the Test It button, the button’s click event handler changes the background color of the selected
element to yellow. Figure 3-2 displays the effect of clicking the Test It button.
Figure 3-2. Highlighted item when the Test It button is clicked
50
www.it-ebooks.info
Chapter 3 ■ jQuery Selectors
3-3. Selecting All the HTML Elements on a Page
Problem
You want to know how to select all the HTML elements on a page.
Solution
The following jQuery selector syntax selects all the HTML elements on a page:
$("*")
The return value is a jQuery object. Listing 3-2 demonstrates the use of jQuery selector to select all the HTML
elements on the page.
Listing 3-2. jQuery selector to select all elements
- Windows Phone Recipes
- Visual C# 2010 Recipes
- UML Applied
- Sharepoint 2010 Designer Guide
- Pro WPF in C# 2010
- Zend Enterprise PHP Patterns
- Web Designer's Reference
- Practical Ajax Projects with Java
- The Definitive Guide to HTML5 WebSocket
- The Essential Guide to HTML5 and CSS3
51
www.it-ebooks.info
Chapter 3 ■ jQuery Selectors
How It Works
In this code, I have listed book titles using the HTML tag - surrounded by ancestors nodes—
, , and
. The page also contains other nodes—,