In the HTML5 API, each node in the page Dom has an classList
object that the programmer can use to add, delete, and modify CSS classes on the node. classList
, programmers can also use it to determine whether a node has been given a CSS class.
First, Element.classlist
classList
There are a number of useful methods in this object:
1 {2 Length: {number},/* # of class on the This element */3 Add: Function () {[native code]},4 contains: function () {[native code]},5 Item: function () {[native code]},/* by index */6 Remove: function () {[native code]},7 Toggle: Function () {[native code]}8}
As you can see above, the Element.classList
classes are small, but each of these methods is useful.
1. New CSS Class
Using the add method, you can add one or more CSS classes to the page element:
Mydiv.classlist. Add (' Mycssclass '); <span style= "Font-family:simsun;" ></span>
2. Delete a CSS class
Using the Remove method, you can delete a single CSS class:
Mydiv.classlist. Remove (' Mycssclass '); <span style= "Font-family:simsun;" ></span>
You can pass in this method a number of class names at a time, separated by spaces, but the result of execution is probably not what you expected.
3, Reverse CSS class has no
Mydiv.classlist. Toggle (' Mycssclass '); Now is the increase of mydiv.classlist. Toggle (' Mycssclass '); Now is the delete
Attention:
- Toggle switch A class,element.toggle (' Class-name ', [Add_or_remove]
- The second parameter of the toggle function is true for add, false for delete
The function of this method is that when the mydiv element does not have this CSS class, it adds this CSS class, if the mydiv element already has this CSS class, it is to delete it. is the reverse operation.
4. Check if a CSS class is included
Mydiv.classlist. contains (' Mycssclass '); Returns TRUE or False
Currently all modern browsers (Mozilla Firefox, Google Chrome, etc.) support this classList
class, so believe that the new JavaScript class library will use classList
classes to manipulate page CSS classes, without having to parse the element node's class attributes as before!
88th Day: Use Classlist to manipulate CSS classes in HTML5