Mastering JavaScript DOM
About Lesson

Add a class to an element

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


// 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.


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

Toggle a class



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 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 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> 

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) => {

Our final output will look as the figure below.

Try out the code
0% Complete