Use the classList in html5.
After years of competition in the JavaScript and JavaScript tool libraries, I often have this dream: When can modern browsers provide helper methods and class libraries to replace those JavaScript tool libraries, such as jQuery, let's replace them with the native method of the browser. I know that browsers will definitely improve in this direction, but this evolution process will not be very rapid, and various browsers need to make such innovations together. Firefox, Google, especially IE, only when these mainstream browsers have such a function can our desire be truly realized. The good news is that one of these features has been added to the HTML5 API: classList.
In HTML5 APIs, each node in the page DOM has a classList object. programmers can use the methods in it to add, delete, and modify CSS classes on nodes. With classList, programmers can also use it to determine whether a node is assigned a CSS class.
Element. classList
There are many useful methods in this classList object:
Copy XML/HTML Code to clipboard
- {
- 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]}
- }
As you can see above, the Element. classList class is very small, but every method in it is very useful.
Add CSS class
Using the add method, you can add one or more css classes to the page elements:
MyDiv. classList. add ('mycssclass ');
Delete a CSS class
With the remove method, you can delete a single CSS class:
MyDiv. classList. remove ('mycssclass ');
You can input multiple class names at a time in this method and separate them with spaces. However, the execution result may not be as expected.
Invert whether or not the CSS class is available
MyDiv. classList. toggle ('mycssclass '); // Add
MyDiv. classList. toggle ('mycssclass '); // Delete
The function of this method is to add this CSS class when the myDiv element does not have this CSS class. If the myDiv element already has this CSS class, it is to delete it. Is the reverse operation.
Check whether a CSS class exists.
MyDiv. classList. contains ('mycssclass '); // returns true or false
Currently, all modern browsers (Firefox, Google, etc.) support this classList class. Therefore, we believe that the new javaScript library will use the classList class to operate the page CSS class, instead of analyzing the class attributes of element nodes as before!
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.