HTML and CSS Reference
In-Depth Information
program. In Chapter 11 when working with forms, we used both the name and id attri-
butes. When working with DOM nodes, the id attribute allows you to specify a specific
node and retrieve a reference to it with the document.getElementByID() method, a DOM1
Although all major browsers are DOM1 compliant, here is a little test code you can
run to check your browser:
if (document.getElementById){
alert("DOM compliant!");
Go to to see examples of
“browser sniffer” programs—programs that can tell what browser is being used.
All that node stuff can be really tricky, but by combining the HTML id attribute with
the getElementById() method of the document object, it is much easier to get a handle on
any HTML object. The getElementById() method takes the id of an HTML element as its
argument and returns a reference to that element. (Remember that getElementById() is
a method of the document object and must be written as document.getElementById() ).
With the reference you can manipulate the element in your JavaScript code. Suppose
you have a paragraph tag defined with an id attribute, as:
< p id="para1" >This is the paragraph.</p>
Now in JavaScript you can get a reference to the p element with the getElementById()
method as follows:
p_element = document.getElementById("para1") ;
Rather than descending the entire DOM tree, p_element is a reference to the p element
identified as “para1” and can be used with the DOM properties:
alert( p_element.nodeName ); // Name of the element
alert( p_element.childNodes[0].nodeValue ); // Text between tags
Example 15.2 demonstrates the use of the id attribute on several HTML elements.
After getting a reference to the element, the DOM node properties can be applied to the
<head><title>The Dom and Id's</title></head>
<body id="body1">
<h1 id="head1">Shortening the DOM Walk</h1>
<p id="para1">This is the paragraph!<p/>
Search WWH ::

Custom Search