You have an element in the DOM and its ID id : "el"
<div id="el"></div>
By using
querySelector
: We can get a reference to that DOM element.
const el = document.querySelector("#el");
Now, we can easily manipulate the classes on that DOM element by using classList Method.
const el = document.querySelector("#el");
// Add a classel.classList.add("open");// Add many classesel.classList.add("this", "little", "piggy");let classes = ["is-message", "is-warning"];el.classList.add(...classes);// Remove a classel.classList.remove("open");// Remove multiple classesel.classList.remove("this", "little", "piggy");// Loop over each classel.classList; // DOMTokenList (pretty much an array)el.classList.forEach(className => {// don't use "class" as that's a reserved wordconsole.log(className);});for (let className of $0.classList) {console.log(className);}el.classList.length; // integer of how many classes there are// Replace a class (replaces first with second)el.classList.replace("is-big", "is-small");// Toggle a class (if it's there, remove it, if it's not there, add it)el.classList.toggle("open");// Remove the classel.classList.toggle("open", false);// Add the classel.classList.toggle("open", true);// Add the class with logicel.classList.toggle("raining", weather === "raining");// Check if element has class (returns true or false)el.classList.contains("open");// Look at individual classes <div class="hot dog">el.classList.item(0); // hotel.classList.item(1); // dogel.classList.item(2); // nullel.classList[1]; // dog
No comments:
Post a Comment