DOM JavaScript
DOM JavaScript
(DOM)
Mendel Rosenblum
window.document.head
window.document.body
● Tree nodes (DOM objects) have tons (~250) of properties, most private
nodeType: 1 (Element)
firstChild
lastChild
parentNode
previousSibing previousSibing
nodeName: #text nodeName: B nodeName: #text
nodeType: 3 (Text) nodeType: 1 nodeType: 3 (Text)
nodeValue: "Sample " nodeValue: " display"
nextSibing nextSibing
firstChild
lastChild parentNode
nodeName: #text
nodeType: 3 (Text)
nodeValue: "bold"
CS142 Lecture Notes - DOM
Accessing DOM Nodes
● Walk DOM hierarchy (not recommended)
element = document.body.firstChild.nextSibling.firstChild;
element.setAttribute(…
● Use DOM lookup method. An example using ids:
HTML: <div id="div42">...</div>
element = document.getElementById("div42");
element.setAttribute(…
● Many: getElementsByClassName(), getElementsByTagName(), …
○ Can start lookup at any element:
document.body.firstChild.getElementsByTagName()
CS142 Lecture Notes - DOM
More commonly used Node properties/methods
● textContent - text content of a node and its descendants
Previous slide example: P Node textContext is "Sample bold display"
● innerHTML - HTML syntax describing the element's descendants.
Previous slide example: P Node innerHTML is "Sample <b>bold</b> display"
● outerHTML - similar but includes element "<p>Sample <b>bold</b> display</p>"
● getAttribute()/setAttribute() - Get or set the attribute of an element
element.className = "active";
window.location.href = "newPage.html";
div2
offsetLeft offsetTop offsetParent
offsetLeft div3
offsetHeight offsetParent
offsetWidth
Parent border
left/offsetLeft
Child margin
Child border
CS142 Lecture Notes - DOM
Element dimensions
● Reading dimensions: element.offsetWidth and element.offsetHeight
#div1 {
width: 50px;
height: 200px;
background: #ffe0e0;
}