Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
63
rated 0 times [  70] [ 7]  / answers: 1 / hits: 15586  / 13 Years ago, fri, june 17, 2011, 12:00:00

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.


More From » javascript

 Answers
66

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

[#91652] Thursday, June 16, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tristab

Total Points: 735
Total Questions: 106
Total Answers: 96

Location: Grenada
Member since Sun, Dec 20, 2020
3 Years ago
tristab questions
Sat, Sep 25, 21, 00:00, 3 Years ago
Sun, Jan 31, 21, 00:00, 3 Years ago
Wed, Dec 2, 20, 00:00, 4 Years ago
Fri, Oct 23, 20, 00:00, 4 Years ago
;