Перейти до основного вмісту
← ⚡ JavaScript & the browser·Модуль C2 · Урок 4
ЗавданняHTML has <button id='b'>toggle</button> and <div id='card' class='card'>Hello</div>. CSS makes .card { padding: 12px } and .card.active { background: gold }. JS: clicking the button toggles 'active' on #card.

classList: перемикання класів сучасним способом

75 XP6 min
Теорія

classList — the cleanest DOM API in the standard library

el.classList.add("active");
el.classList.remove("active");
el.classList.toggle("active");        // adds if missing, removes if present — returns new state
el.classList.contains("active");      // → true / false
el.classList.replace("old", "new");

Every method takes one or more class names. toggle accepts a force boolean too: toggle("active", isOn).

Why classList beats element.className

el.className = "card active";                 // wipes everything else
el.className += " active";                    // string-concat, easy to typo a missing space
el.classList.add("active");                   // surgical, idempotent

className is a string. Mutating it is fragile. classList knows it's a list and acts accordingly.

Combine with CSS for the visual state

A typical pattern:

.dialog        { display: none; }
.dialog.open   { display: block; }
dialog.classList.toggle("open");

State lives in one place: the class. CSS handles the visuals. JS handles the toggle. Each layer does what it's best at.

🔒

Зареєструйся щоб кодувати

Теорія відкрита всім. Інтерактивний редактор, живий перегляд і перевірка відкриваються з 7-денним безкоштовним trial — потрібна картка, скасування у будь-який час.

Реєстрація — безкоштовний trial →

Перші 10 уроків у кожному треку — безкоштовні. Картка не потрібна.

← НазадНаступний урок →

Отримуй одну пораду з Python чи вебу — щодня поштою

Коротко, без води, без спаму. Відписка — в один клік.