DOMTokenList कल्पना के नए संस्करणों में राज्य को बाध्य करने के लिए कई तर्क add()और remove()साथ ही एक दूसरे तर्क की अनुमति है toggle()।
लेखन के समय, Chrome कई तर्कों का समर्थन करता है add()और remove(), लेकिन कोई भी अन्य ब्राउज़र नहीं करता है। IE 10 और निचला, फ़ायरफ़ॉक्स 23 और निचला, क्रोम 23 और निचला और अन्य ब्राउज़र दूसरे तर्क का समर्थन नहीं करते हैं toggle()।
मैंने निम्नलिखित छोटे पॉलीफ़िल को लिखा था कि जब तक समर्थन का विस्तार न हो जाए, तब तक मुझ पर टिकें:
(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;
};
}
})();
ES5 अनुपालन के साथ एक आधुनिक ब्राउज़र और DOMTokenListउम्मीद की जाती है, लेकिन मैं कई विशेष रूप से लक्षित वातावरण में इस पॉलीफ़िल का उपयोग कर रहा हूं, इसलिए यह मेरे लिए बहुत अच्छा काम करता है, लेकिन इसे उन लिपियों के लिए ट्विकिंग की आवश्यकता हो सकती है जो IE 8 और निम्न जैसे विरासत ब्राउज़र वातावरण में चलेंगे। ।