The first thing to do with JavaScript is to find the element that you want to modify. As mentioned earlier, we begin with only one reference to the root node, which is stored in the global variable document. Each node in the DOM is a child of document (or grandchild node, great-grandchildren node, and so on), but it is a manual effort to slowly search through a large and complex document in a step-by-step way. Luckily, we can take some shortcuts. The most common method is to attach a unique ID to an element. In the onload () function of code listing 2-5, we want to look for two elements: paragraph elements, we set styles for it, empty tags, and we add content to it. As you can see, a unique id attribute has been attached to them in HTML, that is, any DOM node could assign an ID to use in a program to get a reference to the node, regardless of its location in the document:
var hello=document.getelementbyid (' Hello ');
Note that this is a method of the Document object. In a simple case as described above (and in many complex cases), the current document object can be accessed through document. If you use an IFRAME (which we will discuss later), you may need to track multiple document objects and determine which document object is being queried.
In some cases, we do need to search the DOM tree step-by-step. Because DOM nodes are organized in a tree structure, each DOM node has no more than one parent node, but can have any number of child nodes. They can be accessed through parentnode and childnodes. ParentNode returns another DOM node, and ChildNodes returns an array of JavaScript nodes that can be traversed, namely:
var children=empty.childNodes;
for (var i=0;i< SPAN>
...
}
Even if there is no unique ID attached to a node in the document, we still have a third way to locate the node conveniently. That is, using the getElementsByTagName () method, search the DOM node based on the type of HTML tag. For example, document.getElementsByTagName ("UL") returns an array containing all the labels in the document.
These methods are useful for manipulating documents that we have little control over [2]. As a general rule, it is safer to use getElementById () than to use getElementsByTagName (), because the former has fewer assumptions about the structure and order of the document, so that the document structure can change independently of the code.