Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How can I get all elements by their class (frequently called getElementsByClass or getElementsByClassName)

Document Object Model (DOM)

How can I get all elements by their class (frequently called getElementsByClass or getElementsByClassName)

by  BillyRayPreachersSon  Posted    (Edited  )
If you wish to find all elements by their class, this is a handy routine. There are many of these around, but I've improved this over time with fixes that I've seen missed out of other similar scripts, such as:

- Workaround for "getElementsByTagName('*');" not working in IE 5.0 or 5.5 for Windows

- Supports finding elements that have multiple class names (so an element will be returned if any of its class names are used as the search parameter)

I've also added the ability to narrow down the scope of the search by passing an optional top-level element to start the search at.

Here's the code:

Code:
function getElementsByClassName(classToFind, baseElement) {
	if (arguments.length == 1) {
		baseElement = document;		// Assume whole document if no base element passed in
	} else if (!baseElement) {
		return([]);					// If base element is passed in and doesn't exist, return empty array
	}	

	var tempElements = baseElement.getElementsByTagName('*');

	// getElementsByTagName('*') doesn't work in IE 5.0/Win or IE 5.5/Win... so use this as a backup
	if (!tempElements.length && baseElement.all) tempElements = baseElement.all;

	var matchingElements = [];
	for (var loop=0; loop<tempElements.length; loop++) {
		if ((' ' + tempElements[loop].className + ' ').indexOf(' ' + classToFind + ' ') != -1) {
			matchingElements[matchingElements.length] = tempElements[loop];
		}
	}
	return(matchingElements);
}

Dan

(Updated 14-Oct-2006 to fix bug with IE returning results even when none were found)

[link http://www.coedit.co.uk/][color #00486F]Coedit Limited[/color][/link][color #000000] - Delivering standards compliant, accessible web solutions[/color]

[tt]Dan's Page [blue]@[/blue] Code Couch
http://www.codecouch.com/dan/[/tt]
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top