VOOZH about

URL: https://www.geeksforgeeks.org/html/html-dom-classlist-property/

⇱ HTML DOM classList Property - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

HTML DOM classList Property

Last Updated : 13 Jun, 2023

The classList Property is a read-only property. This property uses "classList.length" property which returns the class names of the element in the form of DOMTokenlist(set of space-separated tokens). However, this property is to use add, remove and toggle CSS classes on an element.

NOTE: The classList property is not supported in IE9 and earlier. 

Syntax:  

 const elementClasses = elementNodeReference.classList;

Method: 

  • add(class1, class2, ...) : Adds one more class to an element. If above class already exist in the element's class attribute they are ignored. 
     
  • remove(class1, class2, ...) : Removes the specified class from element. Class which does not exist does not throw an error. 
     
  • contains(class) : Checks whether the specified class value exists in the element's class attribute. Returns boolean value accordingly. 
     
  • item(index) : This returns the class value by index in the collection of classes. If the index is out of range it returns null. 
     
  • toggle(class, force) : Toggles between a class name for an element. 
    1. The first parameter removes specified class from an element and returns false. If the class does not exist, it adds class to the element, and the return true.
       
    2. The optional second parameter is a Boolean value that forces the class to be added or removed. When a second parameter is present & evaluates to true, add the specified class value, and if it evaluates to false, it forces to removes the specified class whether it exists or not.


Example-1:Adding and removing a class. 
 

Output : 
 

  • Before adding a class 
     

👁 Image

  • After clicking on add class button 
     

👁 Image

  • After clicking on remove class button 
     

👁 Image


Example-2: Toggling between classes  

Output : 
 

  • Before toggle 
     

👁 Image

  • After toggle 
     

👁 Image


Example-3:  

Output : 
 

  • Before click 
     

👁 Image

  • After click 
     

👁 Image


Supported Browser: The browsers supported by DOM classList Property are listed below:  

  • Google Chrome 22.0 and above
  • Edge 16.0 and above
  • Internet Explorer 10.0 and above
  • Firefox 3.6 and above
  • Opera 11.5 and above
  • Safari 7.0 and above
Comment
Article Tags: