INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Jobs

Document Object Model (DOM)

How can I get all elements by their class (frequently called getElementsByClass or getElementsByClassName) by BillyRayPreachersSon
Posted: 11 Nov 05 (Edited 14 Oct 06)

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)

Coedit Limited - Delivering standards compliant, accessible web solutions

Dan's Page @ Code Couch
http://www.codecouch.com/dan/

Back to Javascript FAQ Index
Back to Javascript Forum

My Archive

Resources

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close