Multimedia Design 2

DOM Cheat Sheet

by Dan Phiffer <dan@phiffer.org>

The Document Object Model is a big part of what makes JavaScript a useful programming language for websites. Simply put, the DOM allows you to inspect, change and establish interactions for a page.

This cheat sheet is not comprehensive, but rather intends to guide you through the most essential parts of the DOM. For a more complete reference guide, see Mozilla's documentation or the W3Schools guide.

document.getElementById('navigation')
Retrieves one element node by 'id' attribute (element with id="navigation")

document.getElementsByTagName('div')
Retrieves a sequence of element nodes by tag name (all divs on the page)

element.getElementsByTagName('div')
Retrieves a sequence of element nodes by tag name contained within an element (all div child elements)

element.childNodes[3]
An array of child nodes contained within an element (the 4th in this example)

element.firstChild
The first child node of an element (identical to element.childNodes[0])

element.nodeName
Returns the tag name of an element (i.e. UL for an unordered list)

element.setAttribute('alt', 'A quixotic gesture')
Sets an attribute of an element (sets alt="A quixotic gesture" for an image in this example)

element.getAttribute('readonly')
Retrieves the value of an attribute (retrieves the attribute readonly in this example)

element.removeAttribute('disabled')
Removes an attribute from an element (enables a form input in this example)

var link = document.createElement('a')
Creates a new element (in this case a link)

element.appendChild(link)
Injects the element into the DOM tree

var dupe = element.cloneNode()
Allows you to create copies of an element

element.innerHTML = '<b>ERROR</b> Input is invalid'
Easily changes the HTML content of an element (not a W3C standard)