ptg16476052
Selecting Elements from the Document 503
18
I pass to jQuery, and it works exactly as it does with CSS. The click() method binds a
function to the onclick event for all the elements matched by the selector it’s called on,
in this case, all the tags on the page.
Selecting Elements from the Document
In the previous example, I used a jQuery selector to bind an event handler to all the links
on a page. The important thing to know about jQuery is that jQuery selectors are a super-
set of CSS selectors; pretty much any selector you can use with CSS can also be used
with jQuery. This is a fantastic shortcut, but it’s worth discussing what happens behind
the scenes a bit as well.
When a web page is loaded in the browser, the browser creates a programmatic repre-
sentation of the page structure called the Document Object Model. This representation of
the page is what’s shown in the Elements tab of the Developer Tools. You’ll notice that
implied tags (like tbody for tables) are included and that broken HTML is repaired in this
representation.
In JavaScript, the built-in document object is the entry point for manipulating the DOM.
It provides methods like getElementById, getElementByName, and getElementByTagName
to enable you to query the DOM directly from JavaScript. There are also methods that
enable developers to add and remove elements from the DOM and to modify them.
However, using these methods is much more cumbersome than using jQuery. For
example, here’s some JavaScript code that accomplishes the same thing as the jQuery
code above a ccessing the DOM directly:
As you can see, that’s an awful lot more code than I wrote for the jQuery example. The
other problem is that this code does not take browser incompatibilities into account.
It works in most browsers, but not all of them. Most of the incompatibilities between
browsers are in their DOM implementations. So if you write code to manipulate the
DOM from scratch, you have to account for these differences. That would entail writing
even more code.