This JavaScript Reference section displays the code for an example program that shows how to add and remove CSS classes from an element to change its style.
<!DOCTYPE html>
<html>
<head>
<title>XoaX.net's Javascript</title>
<script type="text/javascript" src="AddRemoveClasses.js"></script>
<style>
#idBase {
width: 250px;
height: 50px;
}
.cRedBackground {
background-color: #CC0000;
}
.cBlackBorder {
border: 3px solid black;
}
</style>
</head>
<body>
<div style="background-color:#DDFFFF;width:fit-content;padding:25px;">
<div id="idBase"></div>
</div>
<button onclick="ToggleRedBackground()">Toggle Red Background</button>
<button onclick="ToggleBlackBorder()">Toggle Black Border</button>
</body>
</html>
function ToggleRedBackground() {
var qBaseDiv = document.getElementById("idBase");
qBaseDiv.classList.toggle("cRedBackground");
}
function ToggleBlackBorder() {
var qBaseDiv = document.getElementById("idBase");
// Toggle with a different method
if (qBaseDiv.classList.contains("cBlackBorder")) {
qBaseDiv.classList.remove("cBlackBorder");
} else {
qBaseDiv.classList.add("cBlackBorder");
}
}
© 20072026 XoaX.net LLC. All rights reserved.