Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply an array of classes to classList.contains?

Tags:

javascript

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.

like image 945
sdleihssirhc Avatar asked Jun 17 '11 20:06

sdleihssirhc


1 Answers

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;
  };
}
like image 116
user113716 Avatar answered Oct 24 '22 03:10

user113716