How to toggle classes or functions using classlist method in javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Test Page</title>
<script src="main.js"></script>
</head>
<body>
<div id="outer">
<h1 id="selector" style="border: 2px solid dodgerblue; padding : 2px"> RUSTIC TRAVEL JUNKIE</h1>
<p id="para">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illum ipsam blanditiis voluptatibus et, cumque expedita, quam ea! Dolorem obcaecati, fuga, culpa neque, repellat laudantium libero sed sint veritatis praesentium vitae cumque ratione eveniet optio, aspernatur ab. </p>
<button id="inner">CLICK ME</button>
</div>
<script>
document.getElementById("outer").classList.add("classStyle","classColor");
// var a = document.getElementById("outer").classList;
// console.log(a);
//now i want to toggle one of the classes i.e classStyle
document.getElementById("outer").addEventListener("click", abc);
function abc() {
document.getElementById("outer").classList.toggle("classStyle");
var a = document.getElementById("outer").classList;
console.log(a);
}
</script>
</body>
</html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Test Page</title>
<script src="main.js"></script>
</head>
<body>
<div id="outer">
<h1 id="selector" style="border: 2px solid dodgerblue; padding : 2px"> RUSTIC TRAVEL JUNKIE</h1>
<p id="para">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illum ipsam blanditiis voluptatibus et, cumque expedita, quam ea! Dolorem obcaecati, fuga, culpa neque, repellat laudantium libero sed sint veritatis praesentium vitae cumque ratione eveniet optio, aspernatur ab. </p>
<button id="inner">CLICK ME</button>
</div>
<script>
document.getElementById("outer").classList.add("classStyle","classColor");
// var a = document.getElementById("outer").classList;
// console.log(a);
//now i want to toggle one of the classes i.e classStyle
document.getElementById("outer").addEventListener("click", abc);
function abc() {
document.getElementById("outer").classList.toggle("classStyle");
var a = document.getElementById("outer").classList;
console.log(a);
}
</script>
</body>
</html>
Every Time we click the button, we observe that the class classStyle gets toggled:
Comments
Post a Comment
I WOULD APPRECIATE IF YOU LEAVE A COMMENT OR YOUR FEEDBACK HERE !!!