JavaScript DOM Reference

Document

Properties

document.activeElement

Returns the currently focused element.

document.body

Returns the body element.

document.cookie

Gets and sets browser cookies.

document.cookie = 'test=123'
"test=123"
document.cookie = 'test2=456; expires=' + (new Date((new Date()).getTime() + 86400000)).toUTCString();
"test2=789; expires=Tue, 08 Apr 2014 17:54:47 GMT"
document.cookie = 'test3=asdf; path=/banana';
"test3=asdf; path=/banana"
document.cookie
"test=123; test2=789"
function cookieVal(name) {
    var reCookie = new RegExp("[;\\s]" + name + "=([^;]*)", "i"),
        val = reCookie.exec("; " + document.cookie);
    if (val) {
        return decodeURIComponent(val[1]);
    }
    return "";
}

document.title

Gets or sets the value of the document title element.

document.title = 'Sir Loin of Beef';
"Sir Loin of Beef"

Methods

document.createDocumentFragment()

Creates a temporary document fragment to perform DOM manipulations on instead of the active document so each change does not trigger a reflow of the content.

document.createElement(element name)

Returns an HTML element.

document.createElement('p');
<p></p>

document.createTextNode(text)

Creates text to be appended to an element.

document.createTextNode('Lorem ipsum');
"Lorem ipsum"

document.getElementsByTagName(element name)

Returns an array of elements that match the class name parameter. It can also be called on an element other than document to only search inside that element.

document.getElementsByTagName('p').length;
8

document.getElementById(element id)

Returns an element that matches the id name parameter. The id parameter is case-sensitive.

document.getElementById('document');
<div class="section" id="document"></div>

document.querySelector(css style selector)

Returns the first element matching the css selector text.

document.querySelector('h3');
<h3>Properties</h3>

document.querySelectorAll(css style selector)

Returns an array of elements matching the css selector text.

document.querySelectorAll('div.section').length;
3

Window

Properties

window.history

Returns a reference to the history object.

window.innerHeight

Returns the height of the browser window in pixels including, if present, the horizontal scrollbar.

It does not work in IE8. Use this:

window.innerHeight || document.documentElement.clientHeight;
595

window.innerWidth

Returns the width of the browser window in pixels including, if present, the vertical scrollbar.

It does not work in IE8. Use this:

window.innerWidth || document.documentElement.clientWidth;
1043

window.location

Returns a location object.

window.name

Gets and sets a window name for use by hyperlink targets.

window.name = 'giraffe';
"giraffe"
window.name;
"giraffe"

window.parent

Returns a reference to the parent of the current window or frame.

window.screen

Returns a reference to the screen object associated with the window.

window.scrollX

Returns number of pixels the window has been scrolled horizontally. It is an alias for window.pageXOffset.

It does not work in IE8. Use this:

window.pageXOffset || document.documentElement.scrollLeft;
0

window.scrollY

Returns number of pixels the window has been scrolled vertically. It is an alias for window.pageYOffset.

It does not work in IE8. Use this:

window.pageYOffset || document.documentElement.scrollTop;
100

Methods

window.alert

Displays an annoying popup.

alert('foo');

window.clearInterval(interval id)

Cancels a repeated execution created by window.setInterval().

window.clearTimeout(timeout id)

Cancels a delayed execution created by window.setTimeout().

window.close()

Closes the current window if it was created with the window.open() method.

window.confirm(confirmation message)

Displays a popup like window.alert, but has two buttons: OK and Cancel that return true and false, respectively.

if (confirm('Are you sure you want to close this window?')) {
    window.close();
}

window.open(URL, window name, window features)

Opens a new window and returns an object reference to that window. Window features is an optional parameter string.

window.open('popup.html', 'popupTest', 'top=10,left=50,height=500,width=420,location=yes,toolbar=no,status=no,scrollbars=yes');
Window

window.print()

Opens the browser's print dialog. Return undefined when dialog is closed (no matter if it printed or not.)

print();

window.prompt(prompt message, prompt default)

Displays a popup like window.alert, but also allows the user to enter data. It has OK and Cancel buttons like window.confirm. It returns the value entered by the user or null if the cancel button is clicked.

alert(prompt('The next alert box will say anything you want', ''));

window.scroll(x coordinate, y coordinate)

Scrolls window to an (x, y) position.

scroll(0, 0);

window.scrollBy(scroll right, scroll down)

Scrolls window an amount of pixels to the right and down. Negative values will scroll left and up.

scrollBy(0, 100);

window.setInterval(function to execute, delay in ms)

Sets a function to execute repeatedly at a specified time interval. Returns an interval id used with the window.clearInterval() method.

window.setTimeout(function to execute, delay in ms)

Sets a function to execute once after a specified time interval. Returns an interval id used with the window.clearTimeout() method.

window.setTimeout(function () {alert("It's been 5 seconds."); }, 5000);
358

Element

Properties

[Element].attributes

Returns a collection of attribute nodes of a element.

document.getElementsByTagName('a')[0].attributes.href.value
"#"

[Element].className

Gets and sets the value of the class attribute.

[Element].id

Gets and sets the value of the id attribute.

[Element].innerHTML

Quick way to get and set the contents of an element.

document.body.innerHTML = "";
""

[Element].parentElement

Returns the parent element of an element.

document.getElementsByTagName('h1')[0].parentElement;
<div class="article"></div>

[Element].tagName

Gets the tag name of an element object.

Methods

[Element].addEventListener(event type, triggered function, user capture)

function pageLoad() {alert('loaded'); }
document.body.addEventListener('load', pageLoad);

The user capture parameter is optional (defaults to false) and has no equivalent in IE8.

addEventListener() does not work in IE8, so you'll need to use something like this:

function addEvent(el, type, fn) {
    if (el.attachEvent) {
        el['e' + type + fn] = fn;
        el[type + fn] = function () {el['e' + type + fn](window.event); };
        el.attachEvent('on' + type, el[type + fn]);
    } else {
        el.addEventListener(type, fn, false);
    }
}

See the events section for more information.

[Element].getAttribute(attribute name)

Gets the value of an element's named attribute.

document.getElementsByTagName('meta')[0].getAttribute('charset');
"utf-8"

[Element].hasAttribute(attribute name)

Returns a boolean if the attribute exists in the element.

Only works in IE8 in standards mode. (Add this element in the head of the document <meta http-equiv="x-ua-compatible" content="IE=8">.)

document.getElementsByTagName('meta')[0].hasAttribute('charset');
true

[Element].removeAttribute(attribute name)

Removes an attribute from the element.

document.getElementById('element').removeAttribute('class');

[Element].removeEventListener(event type, attached function, user capture)

document.body.removeEventListener('load', pageLoad);

The user capture parameter must match the one use during attachment (if not IE8.) If both types were used, then both need to be removed separately.

removeEventListener() does not work in IE8, so you'll need to use something like this:

function removeEvent(el, type, fn) {
    if (el.detachEvent) {
        el.detachEvent('on' + type, el[type + fn]);
        el[type + fn] = null;
    } else {
        el.removeEventListener(type, fn, false);
    }
}

See the events section for more information.

[Element].setAttribute(attribute name, attribute value)

Sets an attribute value. Adds the attribute to the element if it doesn't already exist.

document.getElementsByTagName('a')[0].setAttribute('href', '#banana');

[Element].getBoundingClientRect()

Returns a TextRectangle object with properties for top, bottom, left, and right coordinates of the element.

document.getElementsByTagName('div')[0].getBoundingClientRect().top;
21

Node

Nodes are parts of a document including HTML elements, text contents, comments and document fragments.

Properties

[Node].childNodes

Returns a NodeList collection.

document.getElementsByTagName('div')[0].childNodes;
NodeList[…]

[Node].firstChild

Returns the first direct child node of a parent node or null if no children exist.

document.getElementsByTagName('div')[0].firstChild;
#text

[Node].lastChild

Returns the last direct child node of a parent node or null if no children exist.

document.getElementsByTagName('ul')[0].lastChild;
<li>…</li>

[Node].nextSibling

Returns the next child node or null if the specified node is last.

document.getElementsByTagName('ul')[0].firstChild.nextSibling;
<li>…</li>

[Node].nodeName

Returns the name of a node. It will commonly be the tag name for HTML elements and #text for text nodes.

document.getElementsByTagName('ul')[0].nodeName;
"UL"

[Node].parentNode

Returns a node's parent node.

document.getElementsByTagName('div')[0].parentNode;
<body>…</body>

[Node].previousSibling

Returns the previous child node or null if the specified node is first.

document.getElementsByTagName('li')[0].lastChild.previousSibling;
<a href="#">Top</a>

[Node].nodeType

Returns a code signifying what type of node it is. 1 - element, 3 - text, 8 - comment, 9 - document, 10 - document type, 11 - document fragment. Other types are deprecated or not pertinent to HTML.

document.body.nodeType;
1

[Node].nodeValue

Returns the value of a text or comment node.

document.getElementsByTagName('h1')[0].firstChild.nodeValue;
"JavaScript DOM Reference"

Methods

[Node].appendChild(new node)

Adds a node inside of a parent node, at the end.

document.body.appendChild(document.createElement('p'));
<p></p>

[Node].hasChildNodes()

Returns a boolean indicating if the node has children.

document.getElementsByTagName('meta')[0].hasChildNodes();
false

[Node].insertBefore(new node, reference node)

Add a node inside a parent node at a position before a reference node.

document.body.insertBefore(document.createElement('p'), document.getElementsByTagName('div')[0]);
<p></p>

[Node].normalize()

Removes empty and combines adjacent text nodes.

document.body.normalize();

[Node].removeChild(node to be removed)

Removes and returns a child node.

document.getElementsByTagName('div')[1].removeChild(document.getElementsByTagName('h1')[0]);
<h1>JavaScript DOM Reference</h1>

[Node].replaceChild(new node, node to be replaced)

Replaces one node with another inside a parent node. Returns the replaced node.

document.body.replaceChild(document.createTextNode('qwerty'), document.body.firstChild);
"\n\n"

NodeList

A NodeList is a collection of nodes. It is not a true array.

Loop through a NodeList like so:

var exampleNodeList, ii, len, item;
exampleNodeList = document.getElementsByTagName('div')[0].childNodes
len = exampleNodeList.length;
for (ii = 0; ii < len; ii = ii + 1) {
  item = exampleNodeList[i];
}

Properties

[NodeList].length

document.getElementsByTagName('div')[0].childNodes.length;
3

Methods

[NodeList].item(node index)

document.getElementsByTagName('div')[0].childNodes.item(1);
<ul>…</ul>

You can use the index directly instead of the item() method in JavaScript.

document.getElementsByTagName('div')[0].childNodes[1];
<ul>…</ul>

Text

Text is one of the types of document nodes.

Methods

[Text].splitText(text index)

document.getElementsByTagName('h1')[0].firstChild.splitText(11).nodeValue;
"DOM Reference"

Location

Use this link to a more complex URL for better examples.

Properties

location.href

The entire URL

location.href;
""

location.protocol

The protocol scheme including the ":" but not the "//"

location.protocol;
""

location.host

The server name and if the port is explicitly included in the URL, a ":" and the port number.

location.host;
""

location.hostname

The server name only.

location.hostname;
""

location.port

The port number, if explicitly in the URL.

location.port;
""

location.pathname

The stuff after the host but before the search (query) string and hash.

location.pathname;
""

location.search

The query (search) string including the "?"

location.search;
""

You can use a function like the one below to parse name/value pairs from the querystring.

function Q$(name) {
    var reQs, val;
    reQs = new RegExp("[\\?&]" + name + "=([^&#]*)", "i");
    val = reQs.exec(parent.location.search);
    if (val) {
        return decodeURIComponent(val[1]);
    }
    return "";
}

location.hash

The hash, including the "#"

location.hash;
""

Methods

location.assign(URL to load)

Load a new page into the browser.

location.assign('http://www.google.com/');

location.reload(force reload)

If the optional parameter is true, it will bypass the local cache.

location.reload(true);

location.replace(URL to load)

This is like .assign() but prevents the current page from being added to history. The back button cannot be used to navigate to it.

location.replace('http://www.google.com/');