294 CHAPTER 6 Essential JavaScript and jQuery
txtInput, so proper IntelliSense can be provided. To take advantage of IntelliSense, the global
variables are eliminated, as shown in the following, modified default.js file.
function initialize() {
clear();
}
function clear() {
$('#txtInput').val('0');
$('#txtResult').val('0');
}
This code is much smaller without the global variables, but the test is now failing because
the test still references the global variables. To fix the test, replace the global variable refer-
ences as follows.
module('QUnit Test Suite', { setup: function () { initialize(); } });
test("Initialize Test", function () {
expect(2);
var expected = '0';
equal($('#txtInput').val(), expected, 'Expected value: ' + expected +
' Actual value: ' + $('#txtInput').val());
equal($('#txtResult').val(), expected, 'Expected value: ' + expected +
' Actual value: ' + $('#txtResult').val());
});
When the test is run, it passes.
Quick check
■■You want to save time when writing JavaScript code. Which library can you use
to accomplish this goal?
Quick check answer
■■Use the jQuery library.
Creating a jQuery wrapper for a DOM element reference
You’ve seen how the use of CSS selectors create a jQuery result, which is a wrapper around
zero to many DOM elements that match the selector. You can also create a jQuery wrapper
from a DOM element reference, as shown in the following examples.
var doc = $(document);
var innerText = $(this).text();
The first expression wraps the document object and assigns the result to a doc variable so
you can use jQuery’s methods with the document object. The second expression wraps the
this object, which is a DOM element being passed to an event listener. After wrapping the