العودة إلى الدورة

Managing Classes: The classList Property

JavaScript: الدورة الكاملة للمبتدئين من 'الصفر إلى الاحتراف'

84. Managing Classes: The classList Property

Instead of directly setting inline styles, modern practice dictates using JavaScript to manage the CSS classes applied to an element. The classList property provides easy methods for this.

HTML & CSS Setup

css .hidden { display: none; } .active { border: 3px solid red; font-weight: bold; }

classList Methods

  1. .add(className): Adds one or more classes.
  2. .remove(className): Removes one or more classes.
  3. .toggle(className): Removes the class if it exists, or adds it if it doesn't.
  4. .contains(className): Returns true if the element has the class.

Example: Toggling Visibility

javascript const menu = document.getElementById('main-menu');

// 1. Check if the element has a class console.log(menu.classList.contains('hidden')); // true

// 2. Remove the 'hidden' class to show it menu.classList.remove('hidden');

// 3. Add the 'active' class menu.classList.add('active');

// 4. Toggle a class based on user click (common use case) const toggleButton = document.getElementById('toggle-btn'); toggleButton.addEventListener('click', () => { menu.classList.toggle('active'); });