Js Add and Remove Class

The classList property offers methods like add, remove, toggle, and contains to work with classes efficiently.


Adding Classes:

The add() method adds one or more classes to an element.

Example
<div id="example">Existing text</div>
<script>
const element = document.getElementById('example');
element.classList.add('new-class'); // Adds a single class
element.classList.add('class1', 'class2'); // Adds multiple classes
console.log(element);
</script>

Try it yourself


Removing Classes:

The remove() method removes one or more classes from an element.

Example
<div id="example" class="new-class class1 class2">Existing text</div>
<script>
const element = document.getElementById('example');
element.classList.remove('new-class'); // Adds a single class
element.classList.remove('class1', 'class2'); // Adds multiple classes
console.log(element);
</script>

Try it yourself


Toggling Classes:

The toggle() method adds a class if it is not present, and removes it if it is.

Example
<div id="example">Existing text</div>
<script>
const element = document.getElementById('example');
// Toggle the 'highlight' class
element.classList.toggle('highlight');
// Optionally force adding or removing
element.classList.toggle('highlight', true); // Always adds the class
element.classList.toggle('highlight', false); // Always removes the class
</script>

Try it yourself


Checking for Classes:

The contains() method checks if an element has a specific class.

Example
<div id="example" class="new-class">Existing text</div>
<script>
const element = document.getElementById('example');
if (element.classList.contains('new-class')) {
console.log('The element has the class!');
} else {
console.log('The element does not have the class.');
}
</script>

Try it yourself


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.