Chapter 3. DOM Traversal and Manipulation

The Document Object Model (DOM for short) is the API provided by the browser to enable you to view and interact with objects (such as elements) in HTML and XML documents. jQuery includes a number of functions that make working with the DOM a lot easier than with JavaScript alone, which can be pretty ugly. However, the functions provided by jQuery can be rather hefty (especially in older browsers), and it is often a lot faster to just use pure JavaScript. Therefore, it is important to know how both work.

Selecting an Element

In jQuery, there is only really one way to select an element, and that is with the CSS selector:

$('#foo');

In JavaScript, there are several ways. You can select elements with their CSS selector (which I will cover later), but it isn’t supported in Internet Explorer versions earlier than 8, so I will cover the traditional methods first.

You can select an element by its Id, ClassName, or TagName. The syntax is pretty similar for all of them:

document.getElementById('foo');
document.getElementsByClassName('bar');
document.getElementsByTagName('p');

The first line, document.getElementById, gets the element with ID foo. As there can only be one element associated with each ID, there is no need to return a NodeList here, and it will return either the element or null.

The second line, document.getElementsByClassName, gets all elements with “bar” as one of their classes. It will return the elements as a NodeList, which is similar ...

Get Learning from jQuery now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.