HTML5 classList API

Having thrust myself into the world of JavaScript and JavaScript Libraries, I've often wondered: When are browser vendors going to see the helper methods/libraries created by the JavaScript toolkits and implement these functionalities natively within the browser? I realize that standards are important and browser vendors can't afford to half-ass these implementations but I do believe they could be...expedited.  The good news is that one of these functionalities has been add to the HTML5 API; classList.

The classList object, added to all nodes within the DOM, provides developers methods by which to add, remove, and toggle CSS classes on a node.  classList also allows developers to check if a CSS class has been assigned to a given node.

Element.classList

The classList object contains a number of helpful methods:

{
	length: {number}, /* # of class on this element */
	add: function() { [native code] },
	contains: function() { [native code] },
	item: function() { [native code] }, /* by index */
	remove: function() { [native code] },
	toggle: function() { [native code] }
}

Element.classList, as you can see, is a small but useful collection of methods.

Adding a CSS Class

The add method allows you to add one more multiple space-separated classes:

myDiv.classList.add('myCssClass');

Removing a CSS Class

The add method allows you to remove a single class:

myDiv.classList.remove('myCssClass');

You could separate multiple classes by space but the result may not be incredibly reliable.

Toggling a CSS Class

myDiv.classList.toggle('myCssClass'); //now it's added
myDiv.classList.toggle('myCssClass'); //now it's removed

Note: If toggle is called and the element does not have the provided CSS class, the class is added.

Contains CSS Class Check

myDiv.classList.contains('myCssClass'); //returns true or false
Some CSS properties may need to be vendor-prefixed.

The classList API is now supported by all modern browsers, so look for the JavaScript libraries to include classList checks instead of parsing an element's class attribute!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值