Home  >  Article  >  Web Front-end  >  Detailed explanation of the use of HTML5's classList attribute to operate CSS classes

Detailed explanation of the use of HTML5's classList attribute to operate CSS classes

黄舟
黄舟Original
2017-10-16 11:13:232395browse

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

Use remove method, you can remove a single CSS class:


document.getElementById("myp").classList.remove("mystyle");

Switch the class name in the element

In the element Switch class name. Use the toggle method, syntax: toggle(class, true|false)

The first parameter is the class name to be removed from the element, and returns false.

If the class name does not exist, the class name will be added to the element and true will be returned.

The second is an optional parameter. Setting a Boolean value is used to set whether the element is forced to add or remove a class, regardless of whether the class name exists. For example:

Remove one

##

document.getElementById("myp").classList.toggle("classToRemove", false);

Add one

 document.getElementById("myp").classList.toggle("classToAdd", true);

Note: Internet Explorer or Opera 12 and earlier versions do not support the second parameter

Check whether it contains a certain class

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn