views:

64

answers:

2

I'm moving some code from YUI to javascript and some of it is using YUI's YAHOO.util.Dom.getElementsBy(function). I've been reading through the prototype API docs and haven't been able to find something equivalent. It needs to be able to take an arbitrary function not just select off a CSS selector or the like. Can anyone suggest to me the best way to accomplish this in Prototype?

A: 

You can use the dollar-dollar function and the filter function :

var elts = $$("div.big").filter(myFunction);
Fabien Ménager
Thanks, this should do the job. I also added another solution I found that provides an alternative approach.
LogicWolfe
A: 

A function by Jack Sleight from http://www.codingforums.com/showthread.php?t=83993 based on getElementsByClassName that accomplishes what I need as is and would be easily extended to take an arbitrary function:

document.getElementsByAttribute = function(attribute, value, tagName, parentElement) {
    var children = ($(parentElement) || document.body).getElementsByTagName((tagName || '*'));
    return $A(children).inject([], function(elements, child) {
        var attributeValue = child.getAttribute(attribute);
        if(attributeValue != null) {
            if(!value || attributeValue == value) {
                elements.push(child);
            }
        }
        return elements;
    });
}
LogicWolfe