HTML5 classList API的使用

写一个dom操作的函数库,发现使用classList API可以方便地操作class。
打开调试窗口,当文档查看:

document.body.classList.add('fuck');
document.body.classList
/**
DOMTokenList
0: "fuck"
length: 1
__proto__: DOMTokenList
add: function add() { [native code] }
constructor: function DOMTokenList() { [native code] }
contains: function contains() { [native code] }
item: function item() { [native code] }
remove: function remove() { [native code] }
toString: function toString() { [native code] }
toggle: function toggle() { [native code] }
__proto__: Object
**/

检测支持

除了IE,现代浏览器都支持。

'classList' in document.createElement('p')

更具体的浏览器支持参考:http://caniuse.com/#search=classList

API

// Add a class to an element  
myElement.classList.add("newClass");  
 
// Remove a class to an element  
myElement.classList.remove("existingClass");  
 
// Check for existence  
myElement.classList.contains("oneClass");  
 
// Toggle a class  
myElement.classList.toggle("anotherClass"); 

注意

用惯了jQuery,看到API,情不自禁地想试下链式调用,但是它不支持链式调用。

document.body.classList.add('test').remove('test');//执行错误
//TypeError: Cannot call method 'remove' of undefined

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>