Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Lesson 2: Working with jQuery CHAPTER 6 289


You can use either of these names to access the library features, so in the interest of mini-
mizing keystrokes, use the dollar sign. First, change the code inside the initialize function of
the default.js file. The code to locate elements can be rewritten to use jQuery and CSS selec-
tors as follows.
function initialize() {
txtInput = $('#txtInput');
txtResult = $('#txtResult');
clear();
}

This code uses the CSS selector to retrieve the elements that match. In this example, there
is only one match for each of the jQuery selectors. The hash (#) symbol indicates that you
want to search for the id of the element. When the statement is executed, the txtInput vari-
able will contain a jQuery object, which is a wrapper object that contains the results. This is
different from the original code, in which the txtInput variable contained a direct reference to
the DOM element. The wrapper object has an array of elements that match the search criteria
or has no elements if there is no match. Even if the query doesn’t match any elements, txtIn-
put still contains the wrapper object, but no elements would be in the results.
When a breakpoint is added to the code after the two statements are executed, you can
debug the code and explore the jQuery wrapper, as shown in Figure 6-11.

FIGURE 6-11 he jQuery wrapper object for T txtInput with one element
Free download pdf