DOM Tutorial
The Document Object Model allows interfacing programming languages with XML documents
by associating them with an object oriented model.
It describes the structure of an XML or HTML document, a web page and allows access to each individual element. We will see in this tutorial that you can modify each element of a page, or create a page or a part through DOM's methods.
This tutorial is based on the DOM 2 Core specification implemented by all browsers
How to use DOM?
DOM is an API, a set of objects with their attributes and methods, an interface for JavaScript.The document object
This is a DOM object corresponding to the current page. However some tags as <iframe> <browser> and <tabbrowser> can introduce other documents into the same window.
Essential methods and attributes of document
- getElementById(x). Returns the tag whose ID is x.
- innerHTML. Attribute to read or assign the content of an ID.
- getElementsByTagName(x). Returns a NodeList, (a list of Node), created for tags whose class (or tag name for XML) is x.
- item(n). Returns the n element inside a NodeList.
- firstChild. Points out the first element inside a Node that is returned by item(n).
- nextSibling. Points out the next element in the Node. Should be used after firstChild.
Essential dynamic methods of document
- createElement(type, name). Create an element, return an Element object (a type of Node).
- appendChild(Node). Add x to the element, as last child.
- insertBefore(Node, Node).
- removeChild(Node).
- setAttribute(name, value). Add attribute to the element.
Example of use with JavaScript
var anchorList = document.getElementsByTagName("a") ;
for(var i = 0; i < anchorList.length; i++)
{
alert("href: " + anchorList[i].href + "\n");
}
This example parses a web page to find links and display them.
- document is an object defined in core DOM to represent the document.
- getElementsByTagName is a method of the object wich builds an array
from each tag matching the parameter, "a" for instance.
- href is a property of HTML DOM.
- anchorList is a declared variable.
DOM interface
We will see the details of interfaces and how to use them in examples: list of attributes, list of methods, access to the content, add elements (example: Include another page), modify the contents, remove items.
- Structure and hierarchy of interfaces of DOM Level 2 Core.
- Node.
- NodeList.
- Document and HTMLDocument.
Case studies
DOM's objects and properties are sufficient to change dynamically graphical element in a webpage.
See also
- The JavaScript programming language. Uses of DOM in JavaScript.
References
- Recommendation from the W3C. DOM 1 defines all the attributes and functions.