开发者

How can I replicate YUI's getElementsBy using Prototype?

开发者 https://www.devze.com 2022-12-24 19:24 出处:网络
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 som

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开发者_StackOverflow中文版 accomplish this in Prototype?


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

var elts = $$("div.big").filter(myFunction);


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;
    });
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号