OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2010 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 /** |
| 6 * @fileoverview This implements the HTML5 HTMLElement classList property. |
| 7 */ |
| 8 |
| 9 // TODO(arv): Remove this when classList is available in WebKit. |
| 10 // https://bugs.webkit.org/show_bug.cgi?id=20709 |
| 11 |
| 12 if (typeof document.createElement('div').classList == 'undefined') { |
| 13 |
| 14 function DOMTokenList(el) { |
| 15 this.el_ = el; |
| 16 } |
| 17 |
| 18 (function() { |
| 19 |
| 20 var re = /\s+/; |
| 21 |
| 22 function split(el) { |
| 23 var cn = el.className.replace(/^\s+|\s$/g, ''); |
| 24 if (cn == '') |
| 25 return []; |
| 26 return cn.split(re); |
| 27 } |
| 28 |
| 29 function DOMException_(code) { |
| 30 this.code = code; |
| 31 } |
| 32 DOMException_.prototype = DOMException.prototype; |
| 33 |
| 34 function assertValidToken(s) { |
| 35 if (s == '') |
| 36 throw new DOMException_(DOMException.SYNTAX_ERR); |
| 37 if (re.test(s)) |
| 38 throw new DOMException_(DOMException.INVALID_CHARACTER_ERR); |
| 39 } |
| 40 |
| 41 DOMTokenList.prototype = { |
| 42 contains: function(token) { |
| 43 assertValidToken(token); |
| 44 return split(this.el_).indexOf(token) >= 0; |
| 45 }, |
| 46 add: function(token) { |
| 47 assertValidToken(token); |
| 48 if (this.contains(token)) |
| 49 return; |
| 50 var cn = this.el_.className; |
| 51 this.el_.className += (cn == '' || re.test(cn.slice(-1)) ? '' : ' ') + |
| 52 token; |
| 53 }, |
| 54 remove: function(token) { |
| 55 assertValidToken(token); |
| 56 var names = split(this.el_); |
| 57 var s = []; |
| 58 for (var i = 0; i < names.length; i++) { |
| 59 if (names[i] != token) |
| 60 s.push(names[i]) |
| 61 } |
| 62 this.el_.className = s.join(' '); |
| 63 }, |
| 64 toggle: function(token) { |
| 65 assertValidToken(token); |
| 66 if (this.contains(token)) { |
| 67 this.remove(token); |
| 68 return false; |
| 69 } else { |
| 70 this.add(token); |
| 71 return true; |
| 72 } |
| 73 }, |
| 74 get length() { |
| 75 return split(this.el_).length; |
| 76 }, |
| 77 item: function(index) { |
| 78 return split(this.el_)[index]; |
| 79 } |
| 80 }; |
| 81 |
| 82 })(); |
| 83 |
| 84 HTMLElement.prototype.__defineGetter__('classList', function() { |
| 85 var tl = new DOMTokenList(this); |
| 86 // Override so that we reuse the same DOMTokenList and so that |
| 87 // el.classList == el.classList |
| 88 this.__defineGetter__('classList', function() { |
| 89 return tl; |
| 90 }); |
| 91 return tl; |
| 92 }); |
| 93 |
| 94 } // if |
OLD | NEW |