I want change the class of a div any time, no mater what class it has. If the div has the class "mystyle" I want it to change into "mystyle1", and vice versa. My code is this:
<!DOCTYPE html>
<html>
<head>
<style>
.mystyle {
width: 300px;
height: 50px;
background-color: coral;
color: white;
font-size: 25px;
}
.mystyle1 {
width: 100px;
height: 100px;
background-color: black;
color: coral;
font-size: 30px;
}
</style>
</head>
<body>
<p>Click the button to change the style class from DIV.</p>
<button onclick="myFunction()">Try it</button>
<div id="myDIV" class="mystyle">
I am a DIV element
</div>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.classList.contains("mysyle")) {
x.classList.replace("mystyle", "mystyle1");
} if (x.classList.contains("mysyle1")) {
x.classList.replace("mystyle1", "mystyle");
}
}
</script>
</body>
</html>
When we press the buttom it has to change the css style any time. But it doesn't. I think that the problem has something to be with the mixed of the conditional (classList.contains) and the classList.replace, because I did it separately and it worked.
Do you know what it is my problem? Thank you.