How to use the remove( ) Method In Javascript

To remove a class name from an element with JavaScript. First style the paragraph with background color. The JavaScript function removeBackgroundColor is defined inside the <script> block. This function is triggered when the button is clicked (onclick="removeBackgroundColor()"). The remove() is called on classList to remove a specified class. It retrieves the paragraph element with the ID myParagraph and removes the class custom-background from it.

Example: Illustration of removing class from paragraph element.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
      <title>Using remove() Method</title>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width,initial-scale=1.0">
    <style>
        body {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100vh;
            margin: 0;
        }
  
        .card {
            width: 300px;
            padding: 20px;
            text-align: center;
            border: 3px solid #755757;
            border-radius: 20px;
        }
  
        h2 {
            color: #3cb369;
        }
  
        .custom-background {
            background-color: #d7f1a7;
            padding: 10px;
        }
  
        button {
            margin-top: 10px;
            padding: 8px;
            cursor: pointer;
            border-radius: 10px;
        }
    </style>
</head>
  
<body>
    <div class="card" id="myCard">
        <h2>w3wiki</h2>
        <p id="myParagraph" class="custom-background">
            The background color will be removed
        </p>
        <div>Click the button to remove the
            "custom-background" class from
            the <p> element
        </div>
        <button onclick="removeBackgroundColor()">
            Click to Remove Color
        </button>
    </div>
    <script>
        function removeBackgroundColor() {
            const paragraph = document.
                getElementById('myParagraph');
            paragraph.classList
                .remove('custom-background');
        }
    </script>
</body>
  
</html>


Output:

Output

How to remove a Class name from an Element using JavaScript ?

Removing a class name from an HTML element using JavaScript is often used to dynamically modify the styling or behavior of an element based on user interactions, events, or other conditions. The operation can be achieved using classList property, that allows you to add, remove, or toggle classes.

Similar Reads

Syntax

paragraph.classList.remove('custom-background');paragraph.classList.toggle('custom-background');...

Using the remove( ) Method

To remove a class name from an element with JavaScript. First style the paragraph with background color. The JavaScript function removeBackgroundColor is defined inside the