Learning JavaScript, 2nd Edition
10.5. The DOM Core Document Object
As you'd expect, the document object is the Core interface to the web-page document. It provides methods to create and remove page elements, as well as control where they occur in the page. It also provides two popular methods for accessing page elements: getElementById and getElementsByTagName. The getElementsByTagName method returns a list of nodes (NodeList) representing all page elements of a specific tag: var list = document.getElementsByTagName("div");
The list can then be traversed, and each node processed for whatever reason.
I've used getElementsByTagName to manage most of my DHTML effects, by encapsulating all dynamically accessible content within DIV tags and then loading all of these elements into a library of customized objects after the page loads. To demonstrate getElementsByTagName, Example 10-8 also uses a frameset to load a source document in one pane and the script document in another. Example 10-8. Frameset opening sample page and active page with script
In this example, the findelem.htm page, shown in Example 10-9, has three page buttons that, when clicked, open prompts for three values: highlight color, source window to open, and element tag for which to search. Example 10-9. Script page opening another document in a frame and highlighting all elements of a given type
The application opens the source document into the first pane and then finds all elements of a type and highlights them with the given colorin this case, the list item elements (LI), which are highlighted in gray, as shown in Figure 10-2. Figure 10-2. Highlighting same-tagged elements
The script can also work within the same document, which makes it effective if you want to highlight all like elements in a page based on some event, e.g., all text-input form elements or thumbnail images. In addition to getElementsByTagName, the document object has several methods that can create new objects. These are demonstrated in the later section "Modifying the Tree." First, though, we'll look at the Element object and the concept of elements in context. |
Категории