getElementsMatching()

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!

Understanding JavaScript Promises E-book Cover

Demystify JavaScript promises with the e-book that explains not just concepts, but also real-world uses of promises.

Download the Free E-book!

The community edition of Understanding JavaScript Promises is a free download that arrives in minutes.