Le versioni più recenti delle specifiche DOMTokenList consentono più argomenti add()e remove(), oltre a un secondo argomento, toggle()per forzare lo stato.
Al momento in cui scrivo, Chrome supporta più argomenti su add()e remove(), ma nessuno degli altri browser lo fa. IE 10 e versioni precedenti, Firefox 23 e versioni precedenti, Chrome 23 e versioni precedenti e altri browser non supportano il secondo argomento toggle().
Ho scritto il seguente piccolo polyfill per risolvermi fino a quando il supporto non si espande:
(function () {
/*global DOMTokenList */
var dummy = document.createElement('div'),
dtp = DOMTokenList.prototype,
toggle = dtp.toggle,
add = dtp.add,
rem = dtp.remove;
dummy.classList.add('class1', 'class2');
// Older versions of the HTMLElement.classList spec didn't allow multiple
// arguments, easy to test for
if (!dummy.classList.contains('class2')) {
dtp.add = function () {
Array.prototype.forEach.call(arguments, add.bind(this));
};
dtp.remove = function () {
Array.prototype.forEach.call(arguments, rem.bind(this));
};
}
// Older versions of the spec didn't have a forcedState argument for
// `toggle` either, test by checking the return value after forcing
if (!dummy.classList.toggle('class1', true)) {
dtp.toggle = function (cls, forcedState) {
if (forcedState === undefined)
return toggle.call(this, cls);
(forcedState ? add : rem).call(this, cls);
return !!forcedState;
};
}
})();
DOMTokenListSono previsti un browser moderno con conformità ES5 , ma sto usando questo polyfill in diversi ambienti specificamente mirati, quindi funziona benissimo per me, ma potrebbe essere necessario modificare gli script che verranno eseguiti in ambienti browser legacy come IE 8 e precedenti .