classlist_polyfill.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. (function () {
  2. if (typeof window.Element === "undefined" ||
  3. "classList" in document.documentElement) {
  4. return;
  5. }
  6. var prototype = Array.prototype,
  7. push = prototype.push,
  8. splice = prototype.splice,
  9. join = prototype.join;
  10. function DOMTokenList(el) {
  11. this.el = el;
  12. // The className needs to be trimmed and split on whitespace
  13. // to retrieve a list of classes.
  14. var classes = el.className.replace(/^\s+|\s+$/g, '').split(/\s+/);
  15. for (var i = 0; i < classes.length; i++) {
  16. push.call(this, classes[i]);
  17. }
  18. }
  19. DOMTokenList.prototype = {
  20. add: function (token) {
  21. if (this.contains(token)) return;
  22. push.call(this, token);
  23. this.el.className = this.toString();
  24. },
  25. contains: function (token) {
  26. return this.el.className.indexOf(token) != -1;
  27. },
  28. item: function (index) {
  29. return this[index] || null;
  30. },
  31. remove: function (token) {
  32. if (!this.contains(token)) return;
  33. for (var i = 0; i < this.length; i++) {
  34. if (this[i] == token) break;
  35. }
  36. splice.call(this, i, 1);
  37. this.el.className = this.toString();
  38. },
  39. toString: function () {
  40. return join.call(this, ' ');
  41. },
  42. toggle: function (token) {
  43. if (!this.contains(token)) {
  44. this.add(token);
  45. } else {
  46. this.remove(token);
  47. }
  48. return this.contains(token);
  49. }
  50. };
  51. window.DOMTokenList = DOMTokenList;
  52. function defineElementGetter(obj, prop, getter) {
  53. if (Object.defineProperty) {
  54. Object.defineProperty(obj, prop, {
  55. get: getter
  56. });
  57. } else {
  58. obj.__defineGetter__(prop, getter);
  59. }
  60. }
  61. defineElementGetter(HTMLElement.prototype, 'classList', function () {
  62. return new DOMTokenList(this);
  63. });
  64. })();