element.classList 將會返回 element 的 class 信息
element.classList:
{
length: {number},
add: function(){},
remove: function(){},
toogle: function(){},
item: function(){},
contanis: function(){}
}
<div class="c1 c2 c3" id="ele"></div>
var ele =document.getElementById('ele');
ele.classList.add('c4');
ele.classList.remove('c2');
ele.classList.toggle('c3'); //移除 c3
ele.classList.toggle('c3'); //添加 c3
ele.classList.contains('c1') // true
ele.classList.contains('c5') // false
ele.classList.contains.itme(0) // c1
使用 toggle 時候,若是class不存在,則增長這個class
檢測瀏覽器是否支持 classList:
'classList' in document.createElement('a') // true 爲支持
瀏覽器支持情況:
Chrome 8+, Firefox 3.6+, Opera 11.5+ , IE 和 Safria 不支持
參考連接:
http://davidwalsh.name/classlist
https://developer.mozilla.org/en/DOM/element.classList