- The Document Object Model (DOM)
- Representation of an HTML document at run time as a collection
of Javascript objects and methods
- Allows a Web page to be queried and modified dynamically under
the control of Javascript
- Overall document structure:
- window (global)
- window.document
- window.document.body
- Node: superclass for all the elements and text of an HTML document:
- Many properties and methods are common to all nodes.
- Key links: parentNode, nextSibling, prevSibling,
firstChild, lastChild.
- Simple example: <p>Sample <b>text</b> display</p>
- Node name is element type (uppercase) or #text.
- Important to use XHTML, since it provides an unambiguous hierarchy.
- How to find HTML elements in Javascript?
- Change the content of an element:
element.innerHTML = "This text is <i>important</i>";
Replaces any existing content (but retains existing element attributes);
causes node structure of DOM to change.
- Change an image (e.g., toggle appearance on clicks):
img.src="newImage.jpg";
- Make element visible or invisible (e.g., for expandable sections):
- Change the appearance of an element (e.g., highlight when mouse passes
over):
- Redirect to a new page:
window.location.href = "newPage.html";
- Create a new element and add it to an existing one:
element = document.createElement("P");
parent.insertBefore(element, sibling);
or,
parent.appendChild(element);
- Simple dialog boxes:
alert("Please click to continue");
if (confirm("Are you sure you want to ...?")) {
...
}
name = prompt("Enter user name here:");
- Coordinates (needed, for example, to position a pop-up menu next to
an existing element, or for drag-and-drop):
- The origin is at the upper left; y increases as you go down.
- Read location with element.offsetLeft, element.offsetTop
These are relative to element.offsetParent, which is not necessarily
the same as element.parentNode (only divs, tables and a few
other elements act as offset parents)
- Dimensions: offsetWidth and offsetHeight include
contents, padding, border, but not margin.
- Positioning elements:
- How to learn what DOM facilities are available?
- Browse the DOM section at
www.w3schools.com, look through the properties and methods
for various elements, such as window and document.
- Warning: w3schools doesn't seem to be absolutely complete (some
features not in Internet Explorer are omitted). The book
Dynamic HTML: The Definitive Reference, by Danny Goodman
is more complete.
- Browser compatibility issues:
- Different browsers support different DOM features.
- In some cases, the same feature is implemented differently
in different browsers.
- The best thing is to use only features that work the same
everywhere.
- www.w3schools.com has tables for each feature listing which
versions of which browsers support it.
- For this class just use Firefox and don't worry
about compatibility with other browsers.