News

Feb 21, 2006 8:24 pm

Invisible Javascript

I just wrote the first bit of javascript for SWAMP. It was just a small task — collapsable menus — but the implementation I chose to attempt was much more difficult than writing a simple onClick event that changed the menu's display. I plan on having all of my javascript completely separate from my HTML. One of the things I needed to do to accomplish this was get a list of a node's children, but only for a specific node type. I decided to write a generic function to do this, so I could re-use it later if I need to do something similar. While I was doing this, I decided that I'm going to make a library of re-usable javascript functions; partially to make it easier for other developers to create complex javascript functionality without too much work, and partially to get a better understanding of javascript (since it is the language that nobody knows and everybody hates). So, without further adieu, here's the function.

// get an element's children, by tag name
// returns an array of elements
function getChildrenByTagName(element, tag_name)
{
	child_array      = new Array();
	tag_name         = tag_name.toLowerCase();
	element_children = element.childNodes;
	
	for (i = 0; i < element_children.length; i++) {
		
		if (element_children[i].tagName != undefined) {
			
			if (element_children[i].tagName.toLowerCase() == tag_name) {
				
				child_array.push(element_children[i]);
			}
		}
	}
	
	return child_array;
}