↑
Main Page
getElementById
<html>
<head>
<title>DOM Example</title>
</head>
<body>
<form method=”post” action=”dosomething.cgi”>
<fieldset>
<legend>What color do you like?</legend>
<input type=”radio” name=”radColor” value=”red” /> Red<br />
<input type=”radio” name=”radColor” value=”green” /> Green<br />
<input type=”radio” name=”radColor” value=”blue” /> Blue<br />
</fieldset>
<input type=”submit” value=”Submit” />
</form>
</body>
</html>
This page asks the user which color he/she likes. The radio buttons all have the same
name
, because you
only want to return one value for this field, which is the
value
attribute of the selected radio button. To
get references to all the radio button elements, you can use the following code:
var oRadios = document.getElementsByName(“radColor”);
You can then manipulate the radio buttons the same way as you can any other element:
alert(oRadios[0].getAttribute(“value”)); //outputs “red”
getElementById()
The second method defined by the HTML DOM is
getElementById()
, which returns an element with
its
id
attribute set to a specific value. In HTML, the
id
attribute is unique — meaning that no two ele-
ments can share the same
id
. This is undoubtedly the fastest method of retrieving a single specific ele-
ment from the document tree.
Suppose you have the following HTML page:
<html>
<head>
<title>DOM Example</title>
</head>
<body>
<p>Hello World!</p>
<div id=”div1”>This is my first layer</div>
</body>
</html>
Internet Explorer 6.0 and Opera 7.5 have a couple of bugs when using this method.
First, they also return elements that have an
id
equal to the given name. Second,
they only check
<input/>
and
<img/>
elements.
172
Chapter 6
09_579088 ch06.qxd 3/28/05 11:37 AM Page 172
Free JavaScript Editor
Ajax Editor
©
→