Java Reference
In-Depth Information
The first of these methods, getElementById() , requires you to ensure that every element you want
to quickly access in the page uses an id attribute, otherwise a null value (a word indicating a
missing or unknown value) will be returned by your method. Let's go back to the first example and
add some id attributes to the elements.
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<h1 id="heading1">My Heading</h1>
<p id="paragraph1">This is some text in a paragraph.</p>
</body>
</html>
Now you can use the getElementById() method to return a reference to any of the HTML elements
with id attributes on your page. For example, if you add the following code in the highlighted
section, you can find and reference the <h1/> element:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<h1 id="heading1">My Heading</h1>
<p id="paragraph1">This is some text in a paragraph.</p>
<script>
alert(document.getElementById("heading1"));
</script>
</body>
</html>
Figure 9-4 shows the result of this code in Firefox.
Note HTMLHeadingElement is an object of the HTML DOM. All HTML
elements have a corresponding reference type in the DOM. See Appendix C
for more objects of the HTML DOM.
You might have been expecting it to return something along the lines of <h1/> or <h1
id="heading1"> , but all it's actually returning is a reference to the <h1/> element. This reference to
the <h1/> element is more useful though, because 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>
<html lang="en">
Search WWH ::




Custom Search