In my HTML, I have a div like so:
<div class="a b c"></div>
In my JavaScript, I have an array of classes that I'm interested in:
var goodClasses = ['a', 'c'];
In good browsers, I can use the awesome classList feature to test whether or not my div has the appropriate classes:
return div.classList.contains(goodClasses[0], goodClasses[1]);
This is okay, but what I'd really like to do is something like this (the syntax is silly, but this is the general idea):
return div.classList.contains.apply(div, goodClasses);
Is there some way to do this? If I have to loop through my array of classes anyway, classList becomes a whole lot less cool.
As @Felix Kling correctly points out, classList.contains accepts only one argument.
If your supported browsers support the every() method on Array, you could do this:
return goodClasses.every( function( c ) {
    return div.classList.contains( c );
});
Browsers that don't support it can use the MDC compatibility fix:
if (!Array.prototype.every)
{
  Array.prototype.every = function(fun /*, thisp */)
  {
    "use strict";
    if (this === void 0 || this === null)
      throw new TypeError();
    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun !== "function")
      throw new TypeError();
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in t && !fun.call(thisp, t[i], i, t))
        return false;
    }
    return true;
  };
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With