Changing the class of a div in JavaScript from one class to another

On my HTML page, I have a div with a CSS class assigned to it. The goal is to switch the current class for another when a button is clicked. It's crucial that not a single CSS property within the class is altered - the entire class must be replaced entirely.

Is this achievable?

I apologize if this question has been addressed before; I wasn't able to locate the information I was seeking. Below is a snippet of the HTML and CSS code:

.class1{
  margin: 20px;
  padding: 20px;
  height: 100px;
  width: 150px;
  color: white;
  background-color: black;
}

.class2{
  margin: 20px;
  padding: 20px;
  height: 100px;
  border-radius: 5px;
  width: 200px;
  color: black;
  background-color: yellow;
}
<html>
<body>
<button>Click</button>
<div class="class1"><p>Hello Everyone</p></div>
</body>
</html>

(I aim to replace the class1 with class2 upon clicking the button using JavaScript.)

Answer №1

var button = document.getElementById('button');
var container = document.getElementById('container');

button.addEventListener('click', function() {
  container.classList.remove('class1');
  container.classList.add('class2');
});
.class1 {
  margin: 20px;
  padding: 20px;
  height: 100px;
  width: 150px;
  color: white;
  background-color: black;
}

.class2 {
  margin: 20px;
  padding: 20px;
  height: 100px;
  border-radius: 5px;
  width: 200px;
  color: black;
  background-color: yellow;
}
<button id="button">Click</button>
<div id="container" class="class1">
  <p>Hello Everyone</p>
</div>

Answer №2

Utilize the classList property to easily remove and add different classes to HTML elements.

function toggleClasses() {
var element = document.querySelector('#elementId');
  element.classList.remove('class1');
  element.classList.add('class2');
}
.class1 {
  margin: 20px;
  padding: 20px;
  height: 100px;
  width: 150px;
  color: white;
  background-color: black;
}

.class2 {
  margin: 20px;
  padding: 20px;
  height: 100px;
  border-radius: 5px;
  width: 200px;
  color: black;
  background-color: yellow;
}
<html>

<body>
  <button onclick="toggleClasses()">Click</button>
  <div id="elementId" class="class1">
    <p>Hello Everyone</p>
  </div>
</body>

</html>

Answer №3

To make changes to elements with the class class1, you can add a click event listener to your button by giving it an id. Use a forEach loop to iterate through all elements with the class class1 and change them to class2.

This method ensures that if there are multiple elements with the class class1, all of them will be changed, not just one.

document.getElementById("btn").addEventListener("click", _ => {
  [...document.getElementsByClassName("class1")].forEach(elem => {
    elem.classList.remove("class1");
    elem.classList.add("class2");
  });
})
.class1 {
  margin: 20px;
  padding: 20px;
  height: 100px;
  width: 150px;
  color: white;
  background-color: black;
}

.class2 {
  margin: 20px;
  padding: 20px;
  height: 100px;
  border-radius: 5px;
  width: 200px;
  color: black;
  background-color: yellow;
}
<button id="btn">Click</button>
<div class="class1">
  <p>Hello Everyone</p>
</div>

If you want to toggle between two classes, you can use the following code snippet:

const index_b = elem.classList.contains("class1");
elem.classList.remove(classes[+!index_b]);
elem.classList.add(classes[+index_b]);

The above code will toggle between two classes in the array named classes, allowing you to switch between them by clicking the button repeatedly.

const classes = ["class1", "class2"];
document.getElementById("btn").addEventListener("click", _ => {
  [...document.getElementsByClassName("toggle")].forEach(elem => {
    const index_b = elem.classList.contains(classes[0]);
    elem.classList.remove(classes[+!index_b]);
    elem.classList.add(classes[+index_b]);
  });
})
.class1 {
  margin: 20px;
  padding: 20px;
  height: 100px;
  width: 150px;
  color: white;
  background-color: black;
}

.class2 {
  margin: 20px;
  padding: 20px;
  height: 100px;
  border-radius: 5px;
  width: 200px;
  color: black;
  background-color: yellow;
}
<button id="btn">Click</button>
<div class="class1 toggle">
  <p>Hello Everyone</p>
</div>

Answer №4

Give this a shot

   <style>
    .class1 {
        margin: 20px;
        padding: 20px;
        height: 100px;
        width: 150px;
        color: white;
        background-color: black;
    }

    .class2 {
        margin: 20px;
        padding: 20px;
        height: 100px;
        border-radius: 5px;
        width: 200px;
        color: black;
        background-color: yellow;
    }
</style>
<script>
    function switchClass() {

        let div = document.getElementsByClassName("class1")[0];

        //or Use by Id

        let div = document.getElementById("class1");
        div.setAttribute("class", "class2");
    }
</script>
<button onclick="switchClass();">Change Style</button>
<div id="class1" class="class1"><p>Hello Everyone</p></div>

Answer №5

One easy way to replace classes is by using the .replace() method.

document.getElementById('example').classList.replace('oldClass', 'newClass');

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling to understand the process of creating a new page in Express

I've created a file called ships.js in my routes folder: var express = require('express'); var router = express.Router(); /* GET Ships page. */ router.get('/ships', function(req, res, next) { res.render('ships', { tit ...

Using boolean flags in JavaScript and jQuery

I'm having trouble setting a boolean flag in JavaScript/jQuery. I thought that the flags should change globally after clicking btn1, but for some reason they remain unchanged when clicking btn2. What am I missing? JavaScript: $(document).ready(funct ...

Frustrated with the endless page loading caused by three.js

I've been trying to incorporate three.js code to showcase a 3D model in GLTF format, but my webpage keeps getting stuck on pre-loading. I need assistance with displaying a preloading page until all the files are fully loaded. Any help in resolving th ...

The selected element does not support the addition of setSelectionRange

I have encountered an error while trying to add the "setSelectionRange" method to an input element that I selected using "getElementById". The error message states that "property 'setselectionrange' does not exist on type 'htmlelement'" ...

Updating Bootstrap 5.3 Modal to Have a Fixed Backdrop when Opened (Using JavaScript/JQuery)

Is there a way to change the backdrop of an open modal to 'static' using jQuery or JavaScript? I want to prevent the user from closing the modal by clicking outside after they have clicked the 'Submit' button on the modal. I've tri ...

What steps can be taken to create a two-column layout using the provided HTML code?

I'm having trouble getting my CSS to work properly in IE 8. Any suggestions on how to fix this? Here's the simplified HTML code I'm using: <div id="column-content"> <div id="content"> <p>This is some text</ ...

Learn how to toggle the display of a div using jQuery, just like the functionality on the popular website

Visit Mashable here Below is the script I am currently using: $(document).ready(function(){ $(".show_hide5").mouseover(function(){ $('.selected').removeClass('selected'); $(this).next().fadeIn("slow").addClass(&apo ...

Utilize Jquery to determine the upload speed bandwidth

Is there a method for measuring upload speed using jquery or javascript? We currently calculate download speed by utilizing pseudostreaming to determine the total time it takes to receive the response. Can we apply a similar technique to measure upload sp ...

Extending a Sub-Object in JavaScript

I'm attempting to include new attributes to the sub-object within object1. However, I am facing issues with it being overwritten. const object1 = { a: 1, b: 2, c: 3, sub: { e: 1, f: 2 } }; const object2 = Object.assign({ j: 4, ...

I am eager to create a Material-UI textfield using an array

My current task involves utilizing TextField based on an Array, but I am facing an issue with dynamically changing all the values. I understand that I can employ ternary conditions to accomplish this task effectively. const TextField = () => { r ...

Issue with Webstorm not automatically updating changes made to JavaScript files

On my HTML page, I have included references to several JavaScript files such as: <script type="text/javascript" src="MyClass.js"></script> When debugging in WebStorm using a Python SimpleHTTPServer on Windows with Chrome, I am able to set bre ...

Is there a way to display a date that is two days before the current date in a React date picker using only vanilla JavaScript

Greetings, I am currently immersed in working with a Shopify app that utilizes React. Unfortunately, I do not have access to their code base or API. The challenge at hand is sending the correct delivery date to the Shopify system. The app currently allows ...

In my experience, the GET request is functioning properly within Postman, but for some reason the POST method continues to send requests repeatedly

ISSUE: I am encountering a problem while making a POST request in Postman. The application keeps sending requests without receiving any response. I have read through various solutions for Postman hanging during a POST request, but none of them seem to sol ...

obtain the image number by extracting a portion of the text

How can I extract the image number from a string using the sub-string function? I have applied the sub-string function to the property below. It returns 3 at the end in Chrome, but it does not work properly in Mozilla. Issue : After "-->", when I chec ...

Modifying the WP FlexSlider plugin to eliminate the previous and next side panels

Is there a way to either reduce the width of the slider's prev/next sides or remove these panels while keeping the arrows to cycle through slides? These elements appear to be within ul.flex-direction-nav. I attempted using ul.flex-direction-nav { dis ...

Retrieve the callback arguments using sinon.spy within a JavaScript promise

During my test with mocha and sinon, I encountered an issue where I couldn't retrieve a callback value from inside a promise scope of an HTTP-request due to the asynchronous nature of promises. It seems that by the time sinon.spy checks on the callbac ...

Reactive Form value is not displaying in view because of FormControlName issue

I have successfully retrieved data from the database and need to pre-fill an update form with preset values. The issue I am facing is that when I add FormControlName to the input field, it removes the preset values. I have tried using setValue and patchV ...

I'm trying to access my navigation bar, but for some reason, it's not allowing me to do so

Having trouble getting the navigation bar to open. I have set it up so that when clicked, it should remove the hide-links tag, but for some reason, it does not toggle properly and keeps the ul hidden. import React from "react"; import { NavLink } ...

Ways to implement a fixed navigation bar beneath the primary navbar using ReactJS

Utilizing ReactJS, I am endeavoring to create a secondary (smaller) navbar in the same style as Airtable's product page. My primary navbar is situated at the top and transitions from transparent to dark when scrolled. The secondary bar (highlighted in ...

One way to achieve the same functionality as onclick in an Ajax call using

I have two JSPs. In the first JSP, I am making an ajax call and receiving data (Ajax body) from the second JSP. However, I am unsure of how to execute jQuery when an argument is present in the function. Everything works fine without an argument. In the ...