Java Reference
In-Depth Information
Methods of the Element Object: Getting and Setting Attributes
If you want to set any element attributes, other than the style attribute, you should use the DOM-
specifi c methods of the Element object.
The three methods you can use to return and alter the contents of an HTML element's attributes are
getAttribute(), setAttribute(), and removeAttribute(), as shown in the following table.
Methods of the Element Object
Description
getAttribute(attributeName)
Returns the value of the supplied attribute. Returns
null or an empty string if the attribute does not exist.
setAttribute(attributeName,
value)
Sets the value of an attribute.
removeAttribute(attributeName)
Removes the value of an attribute and replaces it with
the default value.
Let's take a quick look at how these methods work now.
Try It Out Playing with Attributes
Open your text editor and type the following code.
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<title>Chapter 12: Example 1</title>
</head>
<body>
<p id=”paragraph1”>This is some text.</p>
<script type=”text/javascript”>
var pElement = document.getElementById(“paragraph1”);
pElement.setAttribute(“align”, “center”);
alert(pElement.getAttribute(“align”));
pElement.removeAttribute(“align”);
</script>
</body>
</html>
Save this as ch12_examp1.htm and open it in a browser. You'll see the text of the <p/> element in the
center of the screen and an alert box displaying the text center (Figure 12-6).
Search WWH ::




Custom Search