As any person who uses JavaScript for client side interaction knows, getting elements by their class is one essential thing we need to do over and over again. For the most part using a function equivalent to the one shown below will do.
Code Snippit 1: Simplistic getElementsByClass() JavaScript method
function getElementsByClass( className ) { var all = document.all ? document.all : document.getElementsByTagName( '*' ); var elements = new Array(); for( var e = 0; e < all.length; e++ ) { if (all[e].className == className) { elements[elements.length] = all[e]; } } return elements; }
This function basically checks the string that is entered into the class attribute for each HTML element and returns all elements where there is an exact match.
This method will fail however if we're trying to select elements that have multiple class associations. We need to use something more complex when, for example, creating a list of items that are filterable by class when arranged in overlapping groups. Splitting the class attribute on space characters will allow us to check for matches in these cases:
Code Snippit 2: More advanced getElementsByClass() function
function getElementsByClass( className ) { var all = document.all ? document.all : document.getElementsByTagName( '*' ); var elements = new Array(); for( var e = 0; e < all.length; e++ ) { var classes = all[e].className.split(/\s/g); for( var c = 0; c < classes.length; c++ ) { if( classes == className ) { elements[elements.length] = all[e]; } } } return elements; }
The function above does pretty much the same as the first one, however splits the class attribute string on the spaces and loops through them, trying to match the parts individually. This should match on elements with singular and multiple class names associated with them and solve any problems with multiple classed elements.
- Chris