How to Toggle an Element's Class in Pure JavaScript

Toggle style same as class in pure javascript

You need to check if className is there or not so the code could be:

var sizeBtn = document.querySelector(".size-toggle-btn");
var sizeItems = document.querySelector(".select-items");
var elementHeight = document.querySelector(".Detail-Container__inline").offsetHeight ;

sizeBtn.addEventListener("click", function(e) {
if(sizeItems.classList.contains('size-toggle--active')) {
sizeItems.classList.remove('size-toggle--active')
sizeItems.style.marginTop = null;
}
else{
sizeItems.classList.add('size-toggle--active')
sizeItems.style.marginTop = "-" + elementHeight + "px";
}
});

Toggling Between a CSS class with pure javascript on 'n' elements

There are two simple ways I can think of doing something like this.

First, if you can't designate ID's for each card (which it sounds like you can't), you're going to have to go by class names. Like it was mentioned in the comments, you really don't want to use the same ID for multiple elements.

Part of the reason for this is, as you can see from my examples below, that the .getElementById() method is only meant to return one element, where the other methods like .getElementsByClassName() will return an array of elements.

The problem we're trying to solve is that the sub-content you want to display/hide has to be attached to the element you click somehow. Since we're not using ID's and you can't really rely on class names to be unique between elements, I'm putting the div with the information inside a container with the element that toggles it.

Inside a container div, are two divs for content. One is the main content that's always visible, the other is the sub-content that only becomes visible if the main content is clicked (and becomes invisible when clicked again).

The benefit of this method is that since there are no ID's to worry about, you can copy/paste the cards and they'll each show the same behaviour.

var maincontent = document.getElementsByClassName("main-content");// Note: getElemenstByClassName will return an array of elements (even if there's only one).
for (var i = 0; i < maincontent.length; i++) { //For each element in the maincontent array, add an onclick event. maincontent[i].onclick = function(event) {
//What this does is gets the first item, from an array of elements that have the class 'sub-content', from the parent node of the element that was clicked: var info = event.target.parentNode.getElementsByClassName("sub-content")[0];
if (info.className.indexOf("show") > -1) { // If the 'sub-content' also contains the class 'show', remove the class. info.className = info.className.replace(/(?:^|\s)show(?!\S)/g, ''); } else { // Otherwise add the class. info.className = info.className + " show"; } }}
.container {  border: 1px solid black;  width: 200px;  margin: 5px;}.main-content {  margin: 5px;  cursor: pointer;}.sub-content {  display: none;  margin: 5px;}.show {  /* The class to toggle */  display: block;  background: #ccc;}
<div class="container">  <div class="main-content">Here is the main content that's always visible.</div>  <div class="sub-content">Here is the sub content that's only visible when the main content is clicked.</div></div><div class="container">  <div class="main-content">Here is the main content that's always visible.</div>  <div class="sub-content">Here is the sub content that's only visible when the main content is clicked.</div></div><div class="container">  <div class="main-content">Here is the main content that's always visible.</div>  <div class="sub-content">Here is the sub content that's only visible when the main content is clicked.</div></div>

How to toggle an element with a specific class while having other classes

I changed the event.target.className == to
event.target.className.indexOf("toggle")

Hope this helps.

    var getNextSibling = function (elem, selector) {
// Get the next sibling element var sibling = elem.nextElementSibling;
// If there's no selector, return the first sibling if (!selector) return sibling;
// If the sibling matches our selector, use it // If not, jump to the next sibling and continue the loop while (sibling) { if (sibling.matches(selector)) return sibling; sibling = sibling.nextElementSibling; }};
function toggleDocs(event) { if (event.target && event.target.className.indexOf('toggle') >= 0) {
var toggleContent = getNextSibling(event.target, '.toggle-content');
if (toggleContent.style.display == "none") { toggleContent.style.display = "block";
} else { toggleContent.style.display = "none"; } }}
document.addEventListener('click', toggleDocs, true);
.toggle {   cursor:pointer;}.toggle:hover {    color:#515151;}
.red { color: red; }
//Regular toggle<div class="container">  <div class="toggle">Toggle This Dropdown</div>  <div class="toggle-content" style="display:none">    <ul>      <li><a href="#">How To Do This</a></li>      <li><a href="#">Installing in The Mid 90s</a></li>    </ul></div>
//If toggle class is applied to <h2> and next sibling is //NOT toggle-content<div class="container"> <h2 class="toggle">Click This Dropdown 2</h2> <p>Some random text between the toggle and toggle-content</p> <ul class="toggle-content" style="display:none"> <li><a href="#">Boop</a></li> <li><a href="#">Bop</a></li> </ul></div>
//If the toggle class is applied to <p> and has a red class<div class="container"> <p class="toggle red">Click This Dropdown 3</p> <ul class="toggle-content" style="display:none"> <li><a href="#">Heyo</a></li> <li><a href="#">Hiya</a></li> </ul></div>

toggle child of clicked class pure Javascript - no JQuery

You could easily do this menu with CSS. But here's an example with vanilla JavaScript:

// JS
var submenu = document.getElementsByClassName("submenu-toggle");

for (var i = 0; i < submenu.length; i++) {
submenu[i].addEventListener('click', menus, false);
}

function menus() {
var menu = this.querySelector('.submenu');
menu.classList.toggle("hidden");
};

// CSS

.hidden {
display: none;
}

DEMO - Codepen

How do I supplant jQuery's toggleClass method with pure JavaScript?

Update:
In response to comments, classList.toggle is a pure javascript solution. It has nothing to do with jQuery as one comment implies. If there is a requirement to support old versions of IE then there is a shim (pollyfill) at the MDN link below. And this shim, if needed, is far superior to the accepted answer.

Using classList.toggle certainly seems like the simplest solution. Also see Can I Use classList for browser support.

element.onclick = function() {
'class1 class2'.split(' ').forEach(function(s) {
element.classList.toggle(s);
});
}

Run the snippet to try

box.onclick = function() {  'class1 class2'.split(' ').forEach(function(s) {    box.classList.toggle(s);    stdout.innerHTML = box.className;  });}

/* alternative box.onclick = function() { ['class1', 'class2'].forEach(function(s) { box.classList.toggle(s); stdout.innerHTML = box.className; });}*/
.class1 { background-color: red;}.class2 { background-color: blue;}.class3 { width: 100px; height: 100px; border: 1px black solid;}
click me:<div id="box" class="class1 class3"></div>
<div id="stdout"></div>


Related Topics



Leave a reply



Submit