Javascript Examples and the DOM

A lot of these scripts are copied from DOM Scripting - Web Design with JavaScript and the Document Object Model by Jeremy Keith.

Other examples are taken from JavaScript: The Definitive Guide (5th edition) by David Flanagan. Copyright 2006 O'Reilly Media, Inc., 978-0-596-10199-2.

Table of Contents

Quick Reference

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "">



document.getElementsByTagName() gets list of a, ul, etc document.getElementsByTagName("ul") in this browser
document.getElementById() get's particular ID item document.getElementById("blah") in this browser
element.childNodes get's list of childNodes of element body_element.childNodes in this browser
element.getElementsByTagName() gets all tags below current element in this browser
getAttribute() gets the attribute of a particular node var AVar = document.getElementsByTagName("div");
var danode = AVar[0];
var txt = danode.getAttribute("id");
in this browser

As it turns out this doesn't work in IE6/MS Windows. For example, for a class, try something like:
element['class'] = element['className'] = "monoborder";
sets the attribute of a particular node
var bordertochange = document.getElementById("SetAttrTest");
//bordertochange.class = "monoborder";
//bordertochange['class'] = "monoborder";
bordertochange['className'] = "monoborder";
to see if this actually works. Currently set to the element[... method. If a border surrounds the text then it's working in this browser.

Querying Selected Text

things are not standard - This is taken from JavaScript: The Definitive Guide (5th edition) by David Flanagan. Copyright 2006 O'Reilly Media, Inc., 978-0-596-10199-2.

The getSelection() methods shown do no return selected text within <input> or <textarea>.
function getSelectedText() {
    if (window.getSelection) {
        // This technique is the most likely to be standardized.
        // getSelection() returns a Selection object, which we do not document.
        return window.getSelection().toString();
    else if (document.getSelection) {
        // This is an older, simpler technique that returns a string
        return document.getSelection();
    else if (document.selection) {
        // This is the IE-specific technique.
        // We do not document the IE selection property or TextRange objects.
        return document.selection.createRange().text;

function prouttext() {
    var prouttextid = document.getElementById("prouttext");
    var selectedtext = getSelectedText();
    var prouttext = document.createTextNode(selectedtext);
    var dachildren = prouttextid.childNodes;
    for (var i=0; i<dachildren.length; )

<form><input type=button value="what is selected text" onclick="prouttext();"></form>
<div id="prouttext"></div>
Select some text and press the button below...


Class hierarchy

DOM methods to create markup on the fly

Document.createTextNode()Create a new Text node
Document.creteDocumentFragment()Create doc fragment that you can put children into. When using any the Node methods like .appendChild(), replaceChild(), or .insertBefore(), you pass the fragment, and all the children are appended, replaced, or inserted.
Node.appendChild()adds a node to the doc tree by appending it to the childNodes[] array. If node is already in the doc tree, it is removed and then reinserted at new pos.

Click here to see the function below in action...
function addline(daline) {
    var dv = document.createElement("div")
    var text = document.createTextNode(daline);
    //insert in beginning of doc
    document.body.insertBefore(dv, document.body.firstChild)

Click here to see a more involved function add a table.

Node.replaceChild()replaces the childnode with another
Node.removeChild()removes the childnode
Node.insertBefore()insert node into doc tee before specified child of this node. If already in tree, it is removed and reinserted at its new location.
Element.innerHTMLQuery or insert HTML text representing the children of the element.
function addinnerhtml() {
    var dadiv11 = document.getElementById("dadiv");
    dadiv11.innerHTML = "hello <b>the</b>re";

<div id="dadiv"></div>
<form><input type=button value="insert innerhtml"
 onclick="addinnerhtml(); return(false);"></form>
CharacterData.appendData(), .deleteData(), .insertData(), .replaceData(), substringData()work with text and comment nodes


.length get's length of list body_element.childNodes.length  
nodeValue get/set the value/text of a particular node see below...  
nodeType number is noteType value
Here's some javascript to show the dom structure in a test document.

Basic Javascript placement

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "">
<script type="text/javascript">
JavaScript goes here...
Mark-up goes here...

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "">
<script type="text/javascript" src="file.js">
Mark-up goes here...
Click here to run the javascript test script.


Checking for properties

function checkdocprops) {
	var string44 = "";
	var props44;	
	for (props44 in document.links.namedlink)
		string44 += props44 + "-" + document.links.namedlink[props44] + '\n';

Different ways of getting things from DOM

Changing attributes

Once you get the element node, you can determine an attribute and change it Notes:
trclass = trlist[i].getAttribute('class'); won't work in IE6.
trclass = trlist[i].attributes['class'].nodeValue; will.

Javascript function

Here's a Javascript function. In this case it changes the src attribute of a img tag.
function showPic(whichpic) {
       var source = whichpic.getAttribute("href");
       var placeholder = document.getElementById("placeholder");
It would be called from a href tag.
<a href="images/fireworks.jpg" onclick="showPic(this); return false;" title="A fireworks display">Fireworks</a>
It is intended to change an img tag with an id of "placeholder".
<img id="placeholder" src="images/placeholder.gif" alt="da image gallery">

Changing Text

<form ID="Form1">
<input type=text id="Text1" name=texttochange value="New Title">
<input type=submit value=change onclick="ChangeText(); return false;" ID="Submit1" NAME="Submit1">

function ChangeText() {
var texttochange = document.getElementById("texttochange");
var daText = texttochange.value; //.value used for forms
var changingtitle = document.getElementById("changingtitle")
changingtitle.firstChild.nodeValue = daText;

Here is the input form for the example of the html and javascript above.

Changing Table-Row display note

trlist[i].style.display = "table-row";
IE6 doesn't support "table-row"
setting to "" seems to work

Creating a popup link that degrades gracefully

This also shows an example of more inline javascript...
function popUp(winURL) {,"popup","width=320,height=480");

<a href="" onclick="popUp(this.href); return false;">Example</a>

Adding methods to onload

// written by Simon Willison -
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {

DOM examples to create markup on the fly

Table of Contents Example

// written by Jim Ungar -
// doesn't (totally) work in IE6 - guessing it's because DOM .setAttribute doesn't work in IE6?
function CreateTOC() {
var TOC = document.getElementById("insertTOChere");
var daNodeName, TOCDiv, disNode;
var txt, Htextline, Ahref;
var TOCAName, AName;

//Loop through all elements
var body = document.body;
//this for loop is not totally kosher as we are inserting nodes below (thus the node count changes)
for (i = 0; i < body.childNodes.length; i++) {
// if it's an element
if (body.childNodes[i].nodeType == 1) {
daNodeName = body.childNodes[i].nodeName;
if (daNodeName == "H1" || daNodeName == "H2" || daNodeName == "H3" || daNodeName == "H4" || daNodeName == "H5" || daNodeName == "H6" ) {
//Create a div for the particular TOC line
TOCDiv = document.createElement("div");
//set it up with class HxTOCLine (use for CSS et. al.)
classname = daNodeName + "TOCLINE"; //i.e. H2TOCLINE
TOCDiv['class'] = TOCDiv['className'] = classname;
//Now insert into the end of the Table of Contents

//add the href to the TOC line
TOCAName = "TOCEntry" + i;
TOCPoundAName = "#" + TOCAName;
AHref = document.createElement("a");
//create child for TOCDiv

//add text to the TOC line (inside the Href)
Htextline = body.childNodes[i].firstChild.nodeValue;
txt = document.createTextNode(Htextline);

//add the <a name=...> record that will be href'ed
AName = document.createElement("a");
disNode = body.childNodes[i];
//we've created another node so increment i

sample html...
<b><i>Table of Contents</i></b>
<div id=insertTOChere>

sample css...
<style type="text/css">
.H1TOCLine {margin-left: 0em; color: blue;}
.H2TOCLine {margin-left: 1em; color: blue;}
.H3TOCLine {margin-left: 2em; color: blue;}
.H4TOCLine {margin-left: 3em; color: blue;}
.H5TOCLine {margin-left: 4em; color: blue;}
.H6TOCLine {margin-left: 5em; color: blue;}
#insertTOChere {width: 50%; border: 1px solid black;}

Attaching functions to tags

By attaching functions to tags, you can leave straight HTML in your HTML file, and put the javascript in an associated js file.
window.onload = function() {
if (!document.getElementsByTagName) return false;
var lnks = document.getElementsByTagName("a");
for (var i=0; i if (lnks[i].getAttribute("class") == "popup") {
lnks[i].onclick = function() {
return false;

function popUp(winURL) {,"popup","width=320,height=480");

Spinner example

//grabbed the following from Matthew Barr's blog

//function to display or hide a given element
    function showHideItems(myItem, myButton){
    //this is the ID of the hidden item
    var myItem = document.getElementById(myItem);

    //this is the ID of the plus/minus button image
    var myButton = document.getElementById(myButton);

        if ( != "none") {
            //items are currently displayed, so hide them
   = "none";
        else {
            //items are currently hidden, so display them
   = "block";

//function to swap an image based on its current state
    function swapImage(myImage, state) {

        if (state == "minus") {
            myImage.src = "images/minus.gif";
        else {
            myImage.src = "images/plus.gif";

<a onclick="showHideItems('item1', 'button1');" title="Show/hide items">

<img src="images/plus.gif" border="0" id="button1" name="button1" />

<!-- begin div containing hidden items -->
<div id="item1" style="display:none">

    My hidden content

Fade anything to native background color

// @name      The Fade Anything Technique
// @namespace
// @version   1.0-RC1
// @author    Adam Michela

var Fat = {
	make_hex : function (r,g,b) 
		r = r.toString(16); if (r.length == 1) r = '0' + r;
		g = g.toString(16); if (g.length == 1) g = '0' + g;
		b = b.toString(16); if (b.length == 1) b = '0' + b;
		return "#" + r + g + b;
	fade_all : function ()
		var a = document.getElementsByTagName("*");
		for (var i = 0; i < a.length; i++) 
				var o = a[i];
				var r = /fade-?(\w{3,6})?/.exec(o.className);
				if (r)
						if (!r[1]) r[1] = "";
						if ( Fat.fade_element(,null,null,"#"+r[1]);
	fade_element : function (id, fps, duration, from, to) 
			if (!fps) fps = 30;
			if (!duration) duration = 3000;
			if (!from || from=="#") from = "#FFFF33";
			if (!to) to = this.get_bgcolor(id);
			var frames = Math.round(fps * (duration / 1000));
			var interval = duration / frames;
			var delay = interval;
			var frame = 0;
			if (from.length < 7) from += from.substr(1,3);
			if (to.length < 7) to += to.substr(1,3);
			var rf = parseInt(from.substr(1,2),16);
			var gf = parseInt(from.substr(3,2),16);
			var bf = parseInt(from.substr(5,2),16);
			var rt = parseInt(to.substr(1,2),16);
			var gt = parseInt(to.substr(3,2),16);
			var bt = parseInt(to.substr(5,2),16);

			var r,g,b,h;
			while (frame < frames)
					r = Math.floor(rf * ((frames-frame)/frames) + rt * (frame/frames));
					g = Math.floor(gf * ((frames-frame)/frames) + gt * (frame/frames));
					b = Math.floor(bf * ((frames-frame)/frames) + bt * (frame/frames));
					h = this.make_hex(r,g,b);
					setTimeout("Fat.set_bgcolor('"+id+"','"+h+"')", delay);

					delay = interval * frame; 
			setTimeout("Fat.set_bgcolor('"+id+"','"+to+"')", delay);
	set_bgcolor : function (id, c)
			var o = document.getElementById(id); = c;
	get_bgcolor : function (id)
			var o = document.getElementById(id);
					var c;
					if (window.getComputedStyle) c = window.getComputedStyle(o,null).getPropertyValue("background-color");
					if (o.currentStyle) c = o.currentStyle.backgroundColor;
					if ((c != "" && c != "transparent") || o.tagName == "BODY") { break; }
					o = o.parentNode;
			if (c == undefined || c == "" || c == "transparent") c = "#FFFFFF";
			var rgb = c.match(/rgb\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)/);
			if (rgb) c = this.make_hex(parseInt(rgb[1]),parseInt(rgb[2]),parseInt(rgb[3]));
			return c;

window.onload = function () 

Right Click Context Menu

Keyboard shortcuts

Got this from OpenJS

Use as follows...
shortcut("Ctrl+Shift+X", function() {
        alert("Hi there!");

function shortcut(shortcut,callback,opt) {
	//Provide a set of default options
	var default_options = {
	if(!opt) opt = default_options;
	else {
		for(var dfo in default_options) {
			if(typeof opt[dfo] == 'undefined') opt[dfo] = default_options[dfo];

	var ele =
	if(typeof == 'string') ele = document.getElementById(;
	var ths = this;

	//The function to be called at keypress
	var func = function(e) {
		e = e || window.event;
		//Find Which key is pressed
		if (e.keyCode) code = e.keyCode;
		else if (e.which) code = e.which;
		var character = String.fromCharCode(code).toLowerCase();

		var keys = shortcut.toLowerCase().split("+");
		//Key Pressed - counts the number of valid keypresses - if it is same as the number of keys, the shortcut function is invoked
		var kp = 0;
		//Work around for stupid Shift key bug created by using lowercase - as a result the shift+num combination was broken
		var shift_nums = {
		//Special Keys - and their codes
		var special_keys = {





		for(var i=0; k=keys[i],i 1) { //If it is a special key
				if(special_keys[k] == code) kp++;

			} else { //The special keys did not match
				if(character == k) kp++;
				else {
					if(shift_nums[character] && e.shiftKey) { //Stupid Shift key bug created by using lowercase
						character = shift_nums[character]; 
						if(character == k) kp++;

		if(kp == keys.length) {

			if(!opt['propagate']) { //Stop the event
				//e.cancelBubble is supported by IE - this will kill the bubbling process.
				e.cancelBubble = true;
				e.returnValue = false;

				//e.stopPropagation works only in Firefox.
				if (e.stopPropagation) {
				return false;

	//Attach the function with the event	
	if(ele.addEventListener) ele.addEventListener(opt['type'], func, false);
	else if(ele.attachEvent) ele.attachEvent('on'+opt['type'], func);
	else ele['on'+opt['type']] = func;