Expert Demo: CSS Classes Toggle

Instead of manipulating individual style properties with JavaScript, use CSS classes for better organization and maintainability!

JavaScript can change the style of an HTML element using CSS classes!

💡 Why CSS Classes are Better:

The JavaScript Code:


const demoText = document.getElementById('demo');
const toggleBtn = document.getElementById('toggleBtn');
const addBtn = document.getElementById('addBtn');
const removeBtn = document.getElementById('removeBtn');

// Toggle class on/off
toggleBtn.addEventListener('click', () => {
  demoText.classList.toggle('styled');
});

// Add class only
addBtn.addEventListener('click', () => {
  demoText.classList.add('styled');
});

// Remove class only
removeBtn.addEventListener('click', () => {
  demoText.classList.remove('styled');
});

The CSS Class:

.styled {
  font-size: 35px;
  color: #0d6efd;
  font-weight: bold;
  background-color: #e7f1ff;
  border-color: #0d6efd;
  box-shadow: 0 4px 12px rgba(13, 110, 253, 0.2);
  transform: scale(1.05);
}