In response to a previous post, I was challenged to come up with a way to determine that elements had certain similarities without using CSS queries. Since this may benefit others, I decided to spin off the long comment thread into another post. I’ve called my solution getElementsMatching():

function getElementsMatching(tagName, matcher) {
    var elements = document.getElementsByTagName(tagName);
    var result = [];
    for (var i=0, len=elements.length; i < len; i++){
        if (matcher(elements[i])){
            result.push(elements[i]);
        }
    }
    return result;
}

This function works be accepting a tag name to look for as well as a function that determines if an element passes the test to be included in the resultset. For instance, to return all of the div elements with a class of “special”, you could do the following:

var results = getElementsMatching("div", function (element){
    return (element.className == "special");
});

The second argument should be a function that accepts an element as an argument and returns true if the element should be part of the resultset or false if not.

Of course, this function could be augmented to accept a reference node from which the initial search is conducted (instead of using document as the base), but I think you get the point. Let the flaming begin!

Disclaimer: Any viewpoints and opinions expressed in this article are those of Nicholas C. Zakas and do not, in any way, reflect those of my employer, my colleagues, Wrox Publishing, O'Reilly Publishing, or anyone else. I speak only for myself, not for them.