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.
Adding a Class (add)
document.getElementById ("Mydiv"). Classlist.add ("MyStyle");
To add multiple classes for the <div> element:
document.getElementById ("Mydiv"). Classlist.add ("MyStyle", "Anotherclass", "Thirdclass");
Removing a class (remove)
Using the Remove method, you can delete a single CSS class:
document.getElementById ("Mydiv"). Classlist.remove ("MyStyle");
To remove multiple classes:
document.getElementById ("Mydiv"). Classlist.remove ("MyStyle", "Anotherclass", "Thirdclass");
Toggle Class (toggle)
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.
document.getElementById ("Mydiv"). Classlist.toggle ("Newclassname");
// now is the increase // now is the delete
Whether the class exists (contains)
Check to see if a CSS class is included:
var x = document.getElementById ("mydiv"). Classlist.contains ("MyStyle");
The result is true or false.
Length Property
Returns the number of classes in the class list.
View the number of class names for the <div> element:
var // 3
Gets all the class names for the <div> element:
<div id= "mydiv" class= "MyStyle anotherclass thirdclass" >i am a div element</div>var x = Document.get Elementbyid ("Mydiv"). Classlist;
Item
Index)
Returns the index value of the class name in the element. The index value starts at 0. Returns NULL if the index value is outside the interval range
Gets the first class name of the <div> element (index 0):
var // MyStyle
Browser support
But IE9 and IE9 previous versions do not support this property, the following code can compensate for this regret: (from the Netizen code)
if(! ("Classlist"inchdocument.documentelement) {object.defineproperty (Htmlelement.prototype,' Classlist ', {get:function() { varSelf = This; functionUpdate (FN) {return function(value) {varClasses = Self.className.split (/\s+/g), index=Classes.indexof (value); fn (classes, index, value); Self.classname= Classes.join (""); } } return{add:update (function(classes, index, value) {if(!~index) Classes.push (value); }), Remove:update (function(classes, index) {if(~index) Classes.splice (index, 1); }), Toggle:update (function(classes, index, value) {if(~index) classes.splice (index,1); ElseClasses.push (value); }), contains:function(value) {return!! ~self.classname.split (/\s+/g). IndexOf (value); }, Item:function(i) {returnSelf.className.split (/\s+/g) [I] | |NULL; } }; } }); }
HTML DOM classlist Properties