Mastering JavaScript DOM
About Lesson

https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

Add a class to an element

Note that multiple parameters for the add() isn’t supported in IE 11.

ele.classList.add('classname');

// Add multiple classes (Not supported in IE 11)
ele.classList.add('class1', 'class2', 'class3');

Remove a class from an element

Note that multiple parameters for the remove() isn’t supported in IE 11.

ele.classList.remove('class-name');

// Remove multiple classes (Not supported in IE 11)
ele.classList.remove('class1', 'class2', 'class3');

Toggle a class

ele.classList.toggle('classname');

Examples

Let’s try out some code examples. For complete code check the live example below.

We have a snippet of below HTML fragements.

<ul id="task-list" class="tasks">
      <li id="1" class="task-item" data-complete="true">
        <header class="task-title">Learning JavaScript</header>
        <button class="task-delete-button">x</button> 
        <button class="task-options-button">☰</button> 
      </li>
      <li id="2" class="task-item" data-active="true">
        <header class="task-title">Building React App</header>
        <button class="task-delete-button">x</button> 
        <button class="task-options-button">☰</button> 
      </li>
      <li id="3" class="task-item" data-complete="true">
        <header class="task-title">Building Angular App</header>
        <button class="task-delete-button">x</button> 
        <button class="task-options-button">☰</button> 
      </li>
 </ul>

And we have the following CSS class defined.

.completed {
  text-decoration: line-through;
  color: green;
}

Our task is to find all <header> element within the “li” element that has a “data-complete” attribute to true and add the class “completed” to it. Once this is done the final outpul will reflect the text color green for the selected items.

// Let's select task li with status complete
const tasks = document.querySelectorAll("li[data-complete='true'] header");
tasks.forEach((e) => {
  e.classList.add("completed");
});

Our final output will look as the figure below.

Try out the code

https://codepen.io/rajeshpillai/pen/zYvWWxY?editors=0010
0% Complete