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>