What is the classList in JS?

What is the classList in JS?

JavaScript classList is a DOM property of JavaScript that allows for styling the CSS (Cascading Style Sheet) classes of an element. JavaScript classList is a read-only property that returns the names of the CSS classes.

What is classList in Dom?

The classList property returns the class name(s) of an element, as a DOMTokenList object. This property is useful to add, remove and toggle CSS classes on an element. The classList property is read-only, however, you can modify it by using the add() and remove() methods.

How do you add classList?

Use add() and remove() to add CSS classes to and remove CSS classes from the class list of an element. Use replace() method to replace an existing class with a new one. Use contains() method to check if the class list of an element contains a specified class. Use the toggle() method to toggle a class.

What is toggle in JS?

toggle() The toggle() method of the DOMTokenList interface removes an existing token from the list and returns false . If the token doesn’t exist it’s added and the function returns true .

What does classList do in Javascript?

classList is a read-only property that returns a live DOMTokenList 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 element’s list of classes as a space-delimited string via element.

How do you know if a classList contains a class?

To check if an element contains a class, you use the contains() method of the classList property of the element:

  1. element.classList.contains(className);
  2. const div = document.querySelector(‘.info’); div.classList.contains(‘secondary’); // true.

How does classList toggle work?

toggle() will add the CSS class if it does not exist in the classList array and return true . If the CSS class exists, the method will remove the class and return false . The classList. toggle() method supports adding and removing CSS classes whether they exist or not in your array with shorter lines of code.

What does classList toggle do in JS?

toggle() Method. With each click, classList. toggle() will add the CSS class if it does not exist in the classList array and return true . If the CSS class exists, the method will remove the class and return false .

What is the difference between classList and className?

Using “classList”, you can add or remove a class without affecting any others the element may have. But if you assign “className”, it will wipe out any existing classes while adding the new one (or if you assign an empty string it will wipe out all of them).

Can I use classList contains?

classList. contains(class); This works on all current browsers and there are polyfills to support older browsers too. Otherwise you will also get true if the class you are looking for is part of another class name.

You Might Also Like