views:

39

answers:

1

Hi,

I have an Array of CSS selectors

I want to find if an Element has at least one of the CSS selectors

Example:

var selectors = ['green', 'red', 'yellow']

<div id="elem1" class="red purple yellow white"></div>
<div id="elem2" class="black white"></div>

my function should return true on elem1 and false on elem2

I use prototypejs 1.7_rc2

Thanks for your insights

+1  A: 
function matchesSomeSelectors(element, selectors) {
   return selectors.some(function (selector) {
       return Prototype.Selector.match(element, selector);
   }); 
}

http://jsfiddle.net/4p4LJ/

I'm not sure if some is available in IE or older browsers, but you can easily replicate it yourself if needed.

Here's Mozilla's implementation if you want it:

if (!Array.prototype.some)
{
  Array.prototype.some = function(fun, thisp)
  {
    var i = 0,
        len = this.length >>> 0;

    if (typeof fun != "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (; i < len; i++)
    {
      if (i in this &&
          fun.call(thisp, this[i], i, this))
        return true;
    }

    return false;
  };
}
CD Sanchez