Manipulating attributes
Throughout the first four chapters of this book, we have been using the .addClass(
)
and .removeClass()
methods to demonstrate how we can change the appearance of elements on a page. Effectively, what these two methods are doing is manipulating the class
attribute (or, in DOM scripting parlance, the className
property) of the element. The .addClass()
method creates or adds to the attribute, while .removeClass()
deletes or shortens it. Add to these the .toggleClass()
method, which alternates between adding and removing a class, and we have an efficient and robust way of handling classes.
Nevertheless, the class
attribute is only one of several attributes that we may need to access or change: for example, id
, rel
, and href
. For manipulating these attributes, jQuery provides the .attr()
and .removeAttr()
methods. We could even use .attr()
and .removeAttr()
to modify the class
attribute, but the specialized .addClass()
and .removeClass()
methods are better in this situation...