How To Insert, Delete, Toggle Class In Javascript
In This Javascript Tutorial we will See How To Add, Remove, or Toggle, and Show All className of an HTML element using JS And Netbeans Editor .
Project Source Code:
<!DOCTYPE html>
<html>
<head>
<title>Add - Remove - Toggle - Show Classes</title>
<meta charset="windows-1252">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
div{background-color: #999;width: 200px;height: 80px}
.class1{border:2px solid red;}
.class2{background-color: yellow;}
.class3{margin-left: 50px;}
.class4{width:300px;}
</style>
</head>
<body>
<div class="class2 class3 class4" id="box"></div><br>
<button onclick="addClass();">Add Class</button>
<button onclick="removeClass();">Remove Class</button>
<button onclick="toggleClass();">Toggle Class</button>
<script>
// show element class list
var box = document.getElementById("box");
var cList = box.classList.toString();
console.log(cList);
// add class to the div
function addClass()
{
box.classList.add("class2");
}
// remove class from the div
function removeClass()
{
box.classList.remove("class2");
}
// toggle the class from the div
function toggleClass()
{
box.classList.toggle("class1");
}
</script>
</body>
</html>
<html>
<head>
<title>Add - Remove - Toggle - Show Classes</title>
<meta charset="windows-1252">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
div{background-color: #999;width: 200px;height: 80px}
.class1{border:2px solid red;}
.class2{background-color: yellow;}
.class3{margin-left: 50px;}
.class4{width:300px;}
</style>
</head>
<body>
<div class="class2 class3 class4" id="box"></div><br>
<button onclick="addClass();">Add Class</button>
<button onclick="removeClass();">Remove Class</button>
<button onclick="toggleClass();">Toggle Class</button>
<script>
// show element class list
var box = document.getElementById("box");
var cList = box.classList.toString();
console.log(cList);
// add class to the div
function addClass()
{
box.classList.add("class2");
}
// remove class from the div
function removeClass()
{
box.classList.remove("class2");
}
// toggle the class from the div
function toggleClass()
{
box.classList.toggle("class1");
}
</script>
</body>
</html>
OUTPUT:
default state |
remove class |
add class |
toggle class: click 1 |
toggle class: click 2 |