classList.toggle() मेथड एक क्लास को टॉगल करता है: यदि मौजूद है तो हटा देता है, यदि नहीं है तो जोड़ देता है। वैकल्पिक दूसरे आर्गुमेंट (force) के साथ बलपूर्वक जोड़/हटाया जा सकता है।
उदाहरण
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style>
.newStyle {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
width: 100%; padding: 25px;
background: linear-gradient(135deg, #9350ff, #6f42c1);
color: white; font-size: 25px;
box-sizing: border-box; text-align: center;
border-radius: 8px; transition: all 0.3s;
}
button { padding: 12px 24px; background: #333; color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 16px; }
#sampleDiv { padding: 20px; background: #f8f9fa; border: 2px dashed #ccc; border-radius: 8px; margin: 20px 0; transition: all 0.3s; }
</style> </head> <body>
<h1>JavaScript classList.toggle() उदाहरण</h1>
<button class="btn">क्लास टॉगल करें</button>
<h2>ऊपर दिए गए बटन पर क्लिक करके DIV में क्लास टॉगल करें</h2>
<div id="sampleDiv">यह एक DIV एलिमेंट है।</div>
<script>
document.querySelector(".btn").addEventListener("click", () => {
const element = document.getElementById("sampleDiv");
element.classList.toggle("newStyle");
});
</script> </body> </html>
आउटपुट
पहला क्लिक: क्लास जुड़ती है - स्टाइल लागू होता है
दूसरा क्लिक: क्लास हटती है - मूल स्टाइल वापस
तीसरा क्लिक: फिर से जुड़ती है...
toggle() के उन्नत उपयोग
1. बलपूर्वक मोड (force पैरामीटर)
// force = true → जोड़ें (यदि नहीं है)
element.classList.toggle("active", true); // हमेशा जोड़ता है
// force = false → हटाएं (यदि है)
element.classList.toggle("active", false); // हमेशा हटाता है
// बूलियन एक्सप्रेशन के साथ
const isValid = validateForm();
element.classList.toggle("error", !isValid); // अमान्य होने पर error क्लास
2. रिटर्न वैल्यू
const wasAdded = element.classList.toggle("active");
// wasAdded = true यदि जोड़ा गया, false यदि हटाया गया
3. बहु-क्लास टॉगल (लूप)
["active", "highlight", "focused"].forEach(cls =>
element.classList.toggle(cls)
);
अन्य टॉगल पैटर्न्स
बूलियन एट्रिब्यूट टॉगल
button.toggleAttribute("disabled"); // disabled एट्रिब्यूट टॉगल
button.toggleAttribute("hidden"); // hidden एट्रिब्यूट टॉगल
CSS कस्टम प्रॉपर्टी टॉगल
element.style.setProperty("--theme",
element.style.getPropertyValue("--theme") === "dark" ? "light" : "dark"
);
सावधानी
toggle() केवल एक क्लास पर काम करता है। बहु-क्लास के लिए लूप या अलग कॉल उपयोग करें।