classList.js 2.2 KB

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