GoConqr hat ein neues Design! Sag uns, wie es dir gefällt.

Modul 11 von 21 · Medien

Adding and Removing Classes

Kostas Diakogiannis

Adding and Removing Classes

Adding and removing Classes from DOM elements

Web api's give us the opportunity to add and remove css classes from HTML DOM elements after we have selected them. There are multiple functions to chose from for adding a class, removing a class, toggling a class and more. 

This is extremely useful because we don't need to add and remove a bunch of css properties when a specific event occurs. We can group them in a CSS class and then add or remove the whole class from an element. The following functions on DOM objects help us significantly to achieve what we want.

let section = document.querySelector('section');

section.classList.add('active')  // Add a css class with the name of 'active' to the section elem

section. classList.remove('active')  // Remove the 'active' class from section

section.classList.toggle('active')  // Add a class if not exist, remove it if it does

section.classList.replace(oldClass, newClass)  // This replaces a class with another one

 

Bear in mind that the classList object is not fully supported in older Internet Explorer versions. For being sure there is old another version that can be used in order to just set a CSS class to an element. This is the by applying element.className = 'classNameHere'.

 

Check full docs here on MDN

Anleitung

Um im Kurs weiterzukommen, sende einen Versuch dieses Quiz ab. Du kannst ihn nach der letzten Frage absenden.

Zum gewählten Modul

Feedback

Worum geht es?

Wie gefällt dir das neue Design?

Dein Eindruck