Java Reference
In-Depth Information
Getting and Setting Attributes
All HTML elements have a large number of possible attributes such as
class
,
id
,
src
,
and
href
. The DOM API contains getter and setter methods that can be used to view, add,
remove, or modify the value of any of these attributes.
Getting an Element's Attributes
The
getAttribute()
method returns the value of the attribute provided as an argument:
swim.getAttribute("class");
<< "swim"
var meta = document.getElementsByTagName("meta")[0];
<< undefined
meta.getAttribute("charset");
<< "utf-8"
If an element does not have the given attribute, it returns
null
:
swim.getAttribute("stroke");
<< null
Setting an Element's Attributes
The
setAttribute
can change the value of an element's attributes. It takes two argu-
ments: the attribute that you wish to change and the new value of that attribute.
For example, if we wanted to change the class of the
swim
element to
swimming
, we could
do so using this code:
swim.setAttribute("class", "swimming");
<< undefined
