element remove class

What is element remove class?

In HTML, classes are commonly used to differentiate between different elements. They help developers to style and manipulate specific elements on a webpage.

The remove() method in JavaScript is used to remove a specific class from an HTML element. This method removes the specified class from the element's class list. The remove() method does not throw an error if the element does not have the specified class.

If the element has multiple classes, you can remove a specific class by calling the classList property, which represents the class attribute of an element as a list of individual strings, and then using the remove() method to remove the desired class.

Syntax:

element.classList.remove("classname");

Example:

Suppose we have a div element that has two classes, "box" and "red". We want to remove the "red" class from the div element using JavaScript:

<div id="myDiv" class="box red">
  <p>Hello World!</p>
</div>

<script>
  var myElement = document.querySelector("#myDiv"); // select the div element
  myElement.classList.remove("red"); // remove the "red" class
</script>

After running this code, the div element will only have the "box" class, and the "red" class will be removed.

Alternative Method:

An alternative method to remove a class from an HTML element is to use the replace() method. The replace() method replaces one class with another. So, to remove a class, we can replace it with an empty string.

Syntax:

element.className = element.className.replace("classname", "");

Example:

Using the same example as before, let's remove the "red" class from the div element using the replace() method:

<div id="myDiv" class="box red">
  <p>Hello World!</p>
</div>

<script>
  var myElement = document.querySelector("#myDiv"); // select the div element
  myElement.className = myElement.className.replace("red", ""); // remove the "red" class
</script>

This code will also remove the "red" class from the div element.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe