An HTML element can have more than one CSS class name, and the class attribute holds a list of category names separated by spaces. The identifier class is a reserved word in JavaScript, so you can use classname in JavaScript.
// The following code sets and clears the ClassName property of the element to add or remove the attention class for the element function grabattention (e) {e.classname= "attention";} function releaseattention (e) {e.classname= "";}
However, the classname attribute is an easily misunderstood name: Classnames may be easier to understand. Just like the getElementById () method can return an element, getElementsByTagName (), Getelementsbyclassname (), Getelementsbyname () returns a read-only class array object (NodeList).
The above code assumes that the classname attribute specifies only 0 or one class name, which obviously does not satisfy the need to involve multiple class names in the actual development process.
HTML5 solves this problem by defining the classlist attribute for each element. This property is a Domtokenlist object: A read-only class array object . Referring to the array of classes, you will certainly think of Array.prototype.XX.call (e.classlist) to call the array method. However, the methods defined by Domtokenlist are more practical than the array elements.
1. Add() adds a class name to the class attribute of the element.
2.Remove () clears a class name from the class attribute of the element.
3.Toggle () indicates that an element is added if it does not exist, otherwise it is deleted. Very practical!!! A Toggleclass () method similar to jquery.
4.contains () detects if the class attribute contains a specified name for the classes.
Similar to other DOM collection types, the Domtokenlist object "in real Time" represents a collection of element class names, rather than a static snapshot when querying the Classlist property. Similarly, the Domtokenlist object is bidirectional. The so-called bidirectional is that if a Domtokenlist object is obtained from the classlist attribute of the element, then the classname attribute of the element is changed, and these changes are visible in the identity list in a timely manner. Similarly, change the identity list to be visible in the ClassName attribute in a timely manner. In other words, classlist In addition to the above four important methods, there are real-time, bidirectional characteristics.
In addition to the classlist, there are also the dataset attributes that have been mentioned above are real-time, bi-directional yo.
Note: The NodeList object returned by Queryelementsbytagname (), Queryelementsbyclassname (), Queryelementsbyname () is also in real time, The nodelist returned by Queryselectorall () is not real-time.
From the JavaScript authoritative guide 16.5
Scripted CSS classes-HTML5 classlist properties