Accessing Element Nodes
Chances are you have already seen the
document.getElementById(id) method, which returns the first element with the given
id (there shouldn't be more than one on the page!) or
null if none is found. The following example illustrates how
getElementsByTagName() method of an element node retrieves all descendant (children, grandchildren, etc.) elements of the specified tag name and stores them in a
NodeList, which is similar, but not exactly the same as an array of nodes. The following example illustrates how
getElementsByClassName() method is well supported by browsers and is officially part of HTML5. Applicable to all elements that can have descendant elements,
getElementsByClassName() is used to retrieve all the descendant (children, grandchildren, etc.) elements of a specific class. For example, the following code would return a node list containing all elements of the "warning" class:
var warnings = document.getElementsByClassName("warning");
document.querySelectorAll() method gives you access to elements using the CSS selector syntax. For example, the following code would return a node list containing all list items that are direct children of
var orderedListItems = document.querySelectorAll("ol>li");
document.querySelector() method is the same as
document.querySelectorAll() but rather than returning a node list, it returns only the first element found. The following two lines of code would both return the first list item found in an
var firstOrderedListItem = document.querySelectorAll("ol>li");
var firstOrderedListItem = document.querySelector("ol>li");
this keyword provides access to the current object. It references the object in which it appears.
The following example shows a page (HTMLDOM/Demos/Hierarchy.html) on which a mouse click on any element will display a message giving information about that element's position in the object hierarchy.
Open HTMLDOM/Demos/Hierarchy.html in your browser and play with it, but you don't need to explore the code. It's a complex program and we haven't covered everything in it yet.
When you click on the middle list item, for example, you get the following message:
This shows that the list item's parent is an unordered list (
UL), its first child is a text node ("List Item 2"), its last child is the same as it only has one child, its next and previous siblings are both text nodes, and it has only one child node (the text node). Again, this message was generated in Firefox, but would be the same in other modern browsers.