Element.classlist is a read-only attribute that returns a DOMTokenList containing all of the Element’s existing class attributes.

Using classList is more convenient than element.classname, which is a space-delimited string.

grammar

var elementClasses = elementNodeReference.classList;
Copy the code

ElementClasses is a DOMTokenList that represents the class attributes of elementNodeReference. Elementclasses.length returns 0 if there is no class attribute or if it is empty. The Element.classList itself is read-only, but it can be modified using the add() and remove() methods.

Commonly used method

Add (String [, String]) Adds the given class. The existing class of the element is ignored. Remove (String [,String]) Removes the given class. Item (Number) Returns the class value based on the index position. Toggle (String [, force]) When only one parameter is passed: toggle the class attribute. That is, remove the class and return false if it exists, add it and return true otherwise. If the second argument is passed: add the class if the second argument is true, remove the class if the second argument is false. Contains (String) checks whether the element has a given class.Copy the code
<! DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script> var i = 3; var onLoadFunct = function() { var div = document.getElementById("div"); // div is an object reference to a <div> element, with class="foo bar" div.classList.remove("foo"); div.classList.add("anotherclass"); // If visible exists, remove it, otherwise add div.classList.toggle("visible"); Div. Classlist.toggle ("visible", I < 10); div. Classlist.toggle ("visible", I < 10); alert(div.classList.contains("foo")); div.classList.add("foo", "bar"); <div id='div' class="foo bar"></div> </body> </ HTML >Copy the code

reference

classList API