Java Reference
In-Depth Information
more useful though, as you can use it to alter attributes of the element, such as by changing the color or
size. You can do this via the style object.
<!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>example</title>
</head>
<body>
<h1 id=”heading1”>My Heading</h1>
<p id=”paragraph1”>This is some text in a paragraph</p>
<script type=”text/javascript”>
var h1Element = document.getElementById(“heading1”);
h1Element.style.color = “red”;
</script>
</body>
</html>
If you display this in the browser, you see that you can directly infl uence the attributes of the <h1/>
element in script, as you have done here by changing its text color to red.
The style object points to the style attribute of an element; it allows you to change the CSS style
assigned to an element. The style object will be covered later in the chapter.
The second of the two methods, getElementsByTagName(), works in the same way, but, as its name
implies, it can return more than one element. If you were to go back to the example HTML document
with the table and use this method to return the table cells (<td/>) in your code, you would get a node
list containing a total of four table. You'd still have only one object returned, but this object would be a
collection of elements. Remember that collections are array-like structures, so specify the index num-
ber for the specifi c element you want from the collection. You can use the square brackets if you wish;
another alternative is to use the item() method of the NodeList object, like this:
<!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>This is a test page</title>
</head>
<body>
<span>Below is a table... </span>
<table border=”1”>
<tr>
<td>Row 1 Cell 1</td>
<td>Row 1 Cell 2</td>
</tr>
<tr>
<td>Row 2 Cell 1</td>
<td>Row 2 Cell 2</td>
</tr>
</table>
Search WWH ::




Custom Search