I've written a function that wraps the classList API, allowing you to pass an array of classes to add/remove, or the variable arguments already supported by classList
.
The methods are the following:
var flatten = function(array) {
return Array.prototype.concat.apply([], array);
};
var classMethod = function(method) {
return function(element /*, classes... */) {
return flatten(Array.prototype.slice.call(arguments, 1)).forEach(function(klass) {
element.classList[method](klass);
});
}
};
var addClass = classMethod('add');
var removeClass = classMethod('remove');
Usage:
var elem = document.querySelector('.box');
addClass(elem, 'class1');
addClass(elem, 'class2', 'class3');
addClass(elem, ['class2', 'class3']);
removeClass(elem, 'class1');
removeClass(elem, 'class2', 'class3');
removeClass(elem, ['class2', 'class3']);
I'm wondering if there's some better way to implement this function, say without using the forEach
call and instead using Function.prototype.apply
, but I get a TypeError: Illegal invocation when trying to refactor this into, say:
var classMethod = function(method) {
return function(element /*, classes... */) {
element.classList[method].apply(element, flatten(Array.prototype.slice.call(arguments, 1)));
}
};
Is it possible to write this more succinctly, whilst keeping all of the use cases?