snippetjavascriptTip
HTML element class manipulation with JavaScript
Viewed 0 times
javascriptelementwithmanipulationclasshtml
Problem
Working with HTML elements in the browser often involves around manipulating their classes. In order to do so, you might need a handful of utilities, such as checking if an element has a class, adding, removing or toggling a class.
To check if an HTML element has a class, you can use the
To add a class to an HTML element, you can use the
Similarly, removing a class from an HTML element can be done the same way, but using the
Finally, if you only need to switch a class on and off, you can use the
To check if an HTML element has a class, you can use the
Element.classList property and the DOMTokenList.contains() method.To add a class to an HTML element, you can use the
Element.classList property and the DOMTokenList.add() method.Similarly, removing a class from an HTML element can be done the same way, but using the
DOMTokenList.remove() method, instead.Finally, if you only need to switch a class on and off, you can use the
DOMTokenList.toggle() method.Solution
const hasClass = (el, className) => el.classList.contains(className);
hasClass(document.querySelector('p.special'), 'special'); // trueTo add a class to an HTML element, you can use the
Element.classList property and the DOMTokenList.add() method.Similarly, removing a class from an HTML element can be done the same way, but using the
DOMTokenList.remove() method, instead.Finally, if you only need to switch a class on and off, you can use the
DOMTokenList.toggle() method.Code Snippets
const hasClass = (el, className) => el.classList.contains(className);
hasClass(document.querySelector('p.special'), 'special'); // trueconst addClass = (el, className) => el.classList.add(className);
addClass(document.querySelector('p'), 'special');
// The paragraph will now have the 'special' classconst removeClass = (el, className) => el.classList.remove(className);
removeClass(document.querySelector('p.special'), 'special');
// The paragraph will not have the 'special' class anymoreContext
From 30-seconds-of-code: html-element-test-add-remove-toggle-class
Revisions (0)
No revisions yet.