The Document Object Model is a platform- and language-neutral interface that will allow programs and scripts to dynamically access and update the content, structure and style of documents. The document can be further processed and the results of that processing can be incorporated back into the presented page.
A document is a tree of nodes
These nodes form a model of the document
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Shopping list</title>
</head>
<body>
<h1>What to buy</h1>
<p title="a gentle reminder">Don't forget to buy this stuff.</p>
<ul id="purchases">
<li>A tin of beans</li>
<li>Cheese</li>
<li>Milk</li>
</ul>
</body>
</html>
<p title="a gentle reminder">Don't forget to buy this stuff.</p>
nodeType | Named Constant |
---|---|
1 | ELEMENT_NODE |
2 | ATTRIBUTE_NODE |
3 | TEXT_NODE |
4 | CDATA_SECTION_NODE |
5 | ENTITY_REFERENCE_NODE |
6 | ENTITY_NODE |
7 | PROCESSING_INSTRUCTION_NODE |
8 | COMMENT_NODE |
9 | DOCUMENT_NODE |
10 | DOCUMENT_TYPE_NODE |
11 | DOCUMENT_FRAGMENT_NODE |
12 | NOTATION_NODE |
<p title="a gentle reminder">Don't forget to buy this stuff.</p>
nodeName | nodeType | nodeValue | |
---|---|---|---|
element | P | 1 | null |
attribute | TITLE | 2 | a gentle reminder |
text | #text | 3 | Don't forget to buy this stuff. |
Parents, children and siblings.
Every node is an object.
Every node has properties.
Information about itself: nodeType, nodeName, nodeValue
Information about its family: parentNode, firstChild, nextSibling, etc.
getElementsByTagName
getElementById
getAttribute
setAttribute
li
tags in a document.li { }
document.getElementsByTagName("li")
#purchases { }
document.getElementById("purchases")
li
elements within the element with the ID "purchases".#purchases li { }
document.getElementById("purchases").getElementsByTagName("li")
title
attribute for an element.element.getAttribute("title")
title
attribute for an element to "some text".element.setAttribute("title","some text")
li
elements in the "purchases" element, loop through them all and set the value of each one's title
attribute to "food item".
var list = document.getElementById("purchases");
var items = list.getElementsByTagName("li");
for (var i=0; i < items.length; i++) {
items[i].setAttribute("title","food item");
}
Writing functions