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" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>

Events

Methods

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
setAttribute()

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.setAttribute("class","monoborder");
//bordertochange.class = "monoborder";
//bordertochange['class'] = "monoborder";
bordertochange['className'] = "monoborder";
Click
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.
removeAttributes()

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; )
        prouttextid.removeChild(dachildren[i]);        
    prouttextid.appendChild(prouttext);
}

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

DOM HTML API

Class hierarchy
NodeDocumentHTMLDocument
CharacterDataText
Comment
Attr
ElementHTMLElementHTMLHeadElement
HTMLBodyElement
HTMLTitleElement
HTMLParagraphElement
HTMLInputElement
HTMLTableElement
etc...

DOM methods to create markup on the fly

Document.createElement()
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);
    dv.appendChild(text);
    //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

Attributes/NodeTypes

node.
.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
  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
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" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<script type="text/javascript">
JavaScript goes here...
</script>
</head>
<body>
Mark-up goes here...
</body>
</html>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<script type="text/javascript" src="file.js">
</script>
</head>
<body>
Mark-up goes here...
</body>
</html>
Click here to run the javascript test script.

Examples

Checking for properties

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

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");
       placeholder.setAttribute("src",source);
}
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">
</form>

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) {
window.open(winURL,"popup","width=320,height=480");
}

<a href="http://www.example.com/" onclick="popUp(this.href); return false;">Example</a>
Example

Adding methods to onload

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

DOM examples to create markup on the fly

Table of Contents Example

// written by Jim Ungar - http://jungar.net
// 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.setAttribute("class",classname);
TOCDiv['class'] = TOCDiv['className'] = classname;
//Now insert into the end of the Table of Contents
TOC.appendChild(TOCDiv);

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

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

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

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

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;}
--></style>

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() {
popUp(this.getAttribute("href"));
return false;
}
}
}
}

function popUp(winURL) {
window.open(winURL,"popup","width=320,height=480");
}

Spinner example

//grabbed the following from Matthew Barr's blog
//http://www.matthewbarr.co.uk/blog/archives/12-Using-CSS-and-JavaScript-to-show-and-hide-content.html

//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 (myItem.style.display != "none") {
            //items are currently displayed, so hide them
            myItem.style.display = "none";
            swapImage(myButton,"plus");
        }
        else {
            //items are currently hidden, so display them
            myItem.style.display = "block";
            swapImage(myButton,"minus");
        }
    }

//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
</div>

Fade anything to native background color

// @name      The Fade Anything Technique
// @namespace http://www.axentric.com/aside/fat/
// @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 (o.id) Fat.fade_element(o.id,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);

					frame++;
					delay = interval * frame; 
			}
			setTimeout("Fat.set_bgcolor('"+id+"','"+to+"')", delay);
	},
	set_bgcolor : function (id, c)
	{
			var o = document.getElementById(id);
			o.style.backgroundColor = c;
	},
	get_bgcolor : function (id)
	{
			var o = document.getElementById(id);
			while(o)
			{
					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 () 
	{
	Fat.fade_all();
	}

Right Click Context Menu

http://www.harelmalka.com/rightcontext/?trigger=RIGHT#

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 = {
		'type':'keydown',
		'propagate':false,
		'target':document
	}
	if(!opt) opt = default_options;
	else {
		for(var dfo in default_options) {
			if(typeof opt[dfo] == 'undefined') opt[dfo] = default_options[dfo];
		}
	}

	var ele = opt.target
	if(typeof opt.target == 'string') ele = document.getElementById(opt.target);
	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 = {
			"`":"~",
			"1":"!",
			"2":"@",
			"3":"#",
			"4":"$",
			"5":"%",
			"6":"^",
			"7":"&",
			"8":"*",
			"9":"(",
			"0":")",
			"-":"_",
			"=":"+",
			";":":",
			"'":"\"",
			",":"<",
			".":">",
			"/":"?",
			"\\":"|"
		}
		//Special Keys - and their codes
		var special_keys = {
			'esc':27,
			'escape':27,
			'tab':9,
			'space':32,
			'return':13,
			'enter':13,
			'backspace':8,

			'scrolllock':145,
			'scroll_lock':145,
			'scroll':145,
			'capslock':20,
			'caps_lock':20,
			'caps':20,
			'numlock':144,
			'num_lock':144,
			'num':144,
			
			'pause':19,
			'break':19,
			
			'insert':45,
			'home':36,
			'delete':46,
			'end':35,
			
			'pageup':33,
			'page_up':33,
			'pu':33,

			'pagedown':34,
			'page_down':34,
			'pd':34,

			'left':37,
			'up':38,
			'right':39,
			'down':40,

			'f1':112,
			'f2':113,
			'f3':114,
			'f4':115,
			'f5':116,
			'f6':117,
			'f7':118,
			'f8':119,
			'f9':120,
			'f10':121,
			'f11':122,
			'f12':123
		}


		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) {
			callback(e);

			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) {
					e.stopPropagation();
					e.preventDefault();
				}
				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;
}