This article mainly introduces the detailed explanation of using the classList attribute of HTML5 to operate CSS classes. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look.
Preface
In the past, we needed to use some methods of js or jquery, hasClass, addClass, and removeClass, in the class attribute of an element. Adding or deleting certain classes can meet the needs of certain style changes, but it is still a little troublesome.
h5 The new classList allows us to more conveniently operate on the class names of elements.
Note
classList has poor compatibility and is not compatible with IE browsers below IE10.
Example
classList 点击按钮为p元素添加 "mystyle" 类。
我是一个 p 元素。
##New class
Use add method , you can add one or more classes to page elements:document.getElementById("myp").classList.add("mystyle");
Delete a class
document.getElementById("myp").classList.remove("mystyle");
Switch the class name in the element
##
document.getElementById("myp").classList.toggle("classToRemove", false);
document.getElementById("myp").classList.toggle("classToAdd", true);
Use the contains method to determine whether a certain class exists and return a Boolean value.
//returns true or false document.getElementById("myp").classList.contains("myp");
The above is the detailed content of Detailed explanation of the use of HTML5's classList attribute to operate CSS classes. For more information, please follow other related articles on the PHP Chinese website!