{"id":306845,"date":"2020-04-20T06:58:03","date_gmt":"2020-04-20T13:58:03","guid":{"rendered":"https:\/\/css-tricks.com\/?page_id=306845"},"modified":"2020-05-31T06:04:55","modified_gmt":"2020-05-31T13:04:55","slug":"the-classlist-api","status":"publish","type":"page","link":"https:\/\/css-tricks.com\/snippets\/javascript\/the-classlist-api\/","title":{"rendered":"The .classList() API"},"content":{"rendered":"\n
Assuming you have an element in the DOM:<\/p>\n\n\n\n
<div id=\"el\"><\/div><\/code><\/pre>\n\n\n\nGet a reference to that DOM element:<\/p>\n\n\n\n
const el = document.querySelector(\"#el\");<\/code><\/pre>\n\n\n\nThen you can manipulate the classes on that element with the classList<\/code> method.<\/p>\n\n\n\n\/\/ Add a class\nel.classList.add(\"open\");\n\n\/\/ Add many classes\nel.classList.add(\"this\", \"little\", \"piggy\");\nlet classes = [\"is-message\", \"is-warning\"];\nel.classList.add(...classes);\n\n\/\/ Remove a class\nel.classList.remove(\"open\");\n\n\/\/ Remove multiple classes\nel.classList.remove(\"this\", \"little\", \"piggy\");\n\n\/\/ Loop over each class\nel.classList; \/\/ DOMTokenList (pretty much an array)\nel.classList.forEach(className => {\n \/\/ don't use \"class\" as that's a reserved word\n console.log(className);\n});\nfor (let className of $0.classList) {\n console.log(className);\n}\n\nel.classList.length; \/\/ integer of how many classes there are\n\n\/\/ Replace a class (replaces first with second)\nel.classList.replace(\"is-big\", \"is-small\");\n\n\/\/ Toggle a class (if it's there, remove it, if it's not there, add it)\nel.classList.toggle(\"open\");\n\/\/ Remove the class\nel.classList.toggle(\"open\", false);\n\/\/ Add the class\nel.classList.toggle(\"open\", true);\n\/\/ Add the class with logic\nel.classList.toggle(\"raining\", weather === \"raining\");\n\n\/\/ Check if element has class (returns true or false)\nel.classList.contains(\"open\");\n\n\/\/ Look at individual classes <div class=\"hot dog\">\nel.classList.item(0); \/\/ hot\nel.classList.item(1); \/\/ dog\nel.classList.item(2); \/\/ null\nel.classList[1]; \/\/ dog\n\n<\/code><\/pre>\n\n\nBrowser Support<\/h3>\n\n