Chapter 4. DOM Manipulation Methods

Washed his hands of a deadly fate

He put himself in an altered state

—Devo,

"Mecha-mania Boy"

All of the methods in this chapter manipulate the DOM in some manner. A few of them simply change one of the attributes of an element, while others set an element's style properties. Still others modify entire elements (or groups of elements) themselves—inserting, copying, removing, and so on.

A few of these methods such as .attr(), .html(), and .val() also act as getters, retrieving information from DOM elements for later use.

Gets the value of an attribute for the first element in the set of matched elements.

.attr(attribute)

We can get any attribute of an element rather easily without jQuery, by using the native JavaScript function getAttribute. Additionally, most of these attributes are available through JavaScript as DOM node properties. Some of the more common properties are:

Let's consider the following link:

Using jQuery's .attr method to get an element's attribute has two main advantages:

In order to use getAttribute() or any of an element's properties as a substitute for .attr(), we need to make sure that we are working with a DOM node rather than a jQuery object. To convert the first element represented in a jQuery object to a DOM node, we can use either [0] or .get(0).

All of the following use getAttribute('title') to get its title attribute:

With any of these options, we could replace .getAttribute('title') with .title.

Sets one or more attributes for the set of matched elements.

.attr(attribute, value)
.attr(map)
.attr(attribute, function)