Ahmad Awais Profile picture
CEO ⌘ @CommandCodeAI ❯ Langbase ❯ Ex VP DX ❯ @Google Dev Advisory Board ❯ Award-winning @GitHub Star ❯ @NASA Mars code @SatyaNadella "awesome example for devs"

Sep 27, 2021, 12 tweets

Crash Course on the .classList() Web API.

Thread πŸ§΅πŸ‘‡

πŸ‘‹Howdy, it's Awais @MrAhmadAwais β€” Head of Developer Relations at RapidAPI. Google Devs Expert, GitHub Star, DO Navigator.

I've coded 100s of open-source software used by millions of devs. Contributed to NASA’s Mars Helicopter mission. Learn more β†’ Awais.dev/about

πŸ‘‡

If you write code for the Web, there are a large number of Web APIs available.

Web APIs are typically used with JavaScript.

One such API is the .classList() API.

Let's learn how to use it well. πŸ‘‡

The .classList() API 🧠

The Element.classList is a read-only property that returns a live DOMTokenList collection of the class attributes of the element.

It can be used to manipulate the class list.

The .classList() API 🧠

πŸ‘¨β€πŸ’» Syntax:

// HTML.
<div class="cover"></div>

// JavaScript.
const div = document.querySelector(".cover");

You can access the classList like this:
div.classList;

Returns a DOMTokenList. It's 0th indexed with JS Array objects. Always case-sensitive.

ADD with the .classList() API 🧠

// Add a class.
div.classList.add("colors");

// Add more than one classes.
div.classList.add("colors", "size");

// Spread works!
const classes = ["size", "colors"];
div.classList.add(...classes);

REMOVE with the .classList() API 🧠

// Remove a class.
div.classList.remove("colors");

// Remove many classes.
div.classList.remove("colors", "size");

// Spread works!
const classes = ["size", "colors"];
div.classList.remove(...classes);

TOGGLE with the .classList() API 🧠

// Toggle a class.
div.classList.toggle("colors");

If the "colors" class is present, remove it, if it's not there, add it.

REPLACE with the .classList() API 🧠

// Replace a class.
div.classList.replace("colors", "purple");

This replaces the class "colors" with class "purple".

CHECK with the .classList() API 🧠

// Check if the element has a class.
div.classList.contains("colors");

It returns true or false.

VIEW with the .classList() API 🧠

// View individual classes.
// For this HTML <div class="colors size">
div.classList.item(0); // colors
div.classList.item(1); // size
div.classList.item(2); // null
div.classList[1]; // colors

Liked this thread? Do this ↓

1️⃣ Retweet the first tweet:


2️⃣ Follow me for more @MrAhmadAwais β€” NTMY!

3️⃣ Reply to share feedback on would you like me to post more such threads on Web Development and other #OneDevMinute tips & tricks?

Peace! ✌️

Share this Scrolly Tale with your friends.

A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.

Keep scrolling