Return to Snippet

Revision: 55249
at January 31, 2012 15:00 by cjcenizal


Initial Code
function getElement( selector ) {
	var split = selector.split(" ");
	var el = document;
	var len = split.length;
	var type, name;
	for( var i = 0; i < len; i++ ) {
		try {
			name = split[ i ];
			type = name[ 0 ];
			name = name.substr( 1, name.length - 1 );
			switch( type ) {
				case "#":
					el = goog.dom.getElement( name, el );
					break;
				case ".":
					el = goog.dom.getElementByClass( name, el );
					break;
				default:
					el = null;
			}
		} catch( e ) {	
			el = null;
			throw( "Error with getElement using selector: " + selector + ", error: " + e );
		}
	}
	if ( el == document ) el = null;
	return el;
}

Initial URL


Initial Description
The Google Closure lets you get DOM elements with getElement( id ) and getElementByClass( class ).  This function combines the two to let you get elements similarly to the way jQuery does.  E.g. getElement( '#home .sidebar #links') returns the element with an id of 'links', within the element of class 'sidebar', within the element of id 'home'.

Initial Title
Get DOM element via class and id selector, using Google Closure

Initial Tags
javascript, google, DOM

Initial Language
JavaScript