Element.classList | div add class js
TheElement.classListisaread-onlypropertythatreturnsaliveDOMTokenList[1]collectionoftheclassattributesoftheelement.Thiscanthenbeusedtomanipulatetheclasslist.UsingclassListisaconvenientalternativetoaccessinganelementslistofclassesasaspace-delimitedstringviaelement.className[2].ADOMTokenList[3]representingthecontentsoftheelementsclassattribute.Iftheclassattributeisnotsetorempty,itreturnsanemptyDOMTokenList,i.e.aDOMTokenListwiththelengthpropertyequalto0.AlthoughtheclassListpropertyitselfisread-o...
The Element.classList is a read-only property that returns a live DOMTokenList[1] collection of the class attributes of the element. This can then be used to manipulate the class list.
Using classList is a convenient alternative to accessing an elements list of classes as a space-delimited string via element.className[2].
A DOMTokenList[3] representing the contents of the elements class attribute. If the class attribute is not set or empty, it returns an empty DOMTokenList, i.e. a DOMTokenList with the length property equal to 0.
Although the classList property itself is read-only, you can modify its associated DOMTokenList using the add()[4], remove()[5], replace()[6], and toggle()[7] methods.
const div = document.createElement(div); div.className = foo; console.log(div.outerHTML); div.classList.remove("foo"); div.classList.add("anotherclass"); console.log(div.outerHTML); div.classList.toggle("visible"); div.classList.toggle(...