How to Toggle Class Using Pure JavaScript in HTML

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 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>

Add/Remove class when clicking on element with pure JavaScript

Basically you are looping within your loop twice. I have fixed that.
You simply need to remove the previous active class and add new one like this:

  document.querySelector(".sidenav a.active-list").classList.remove("active-list");
e.target.classList.add('active-list');

You can this: codepen:link https://codepen.io/emmeiWhite/pen/jOMZRxd

let elements = document.querySelectorAll('div, ul, li, a');

elements.forEach(i => {
i.addEventListener('click', function(e) {
document.querySelector(".sidenav a.active-list").classList.remove("active-list");
e.target.classList.add('active-list');

});
});
.sidenav {
width: 130px;
position: fixed;
z-index: 1;
top: 20px;
left: 10px;
overflow-x: hidden;
}

.sidenav ul {
background-color: black;
list-style: none;
padding: 0px;
padding-right: 0px;
}

.sidenav > ul > li {
color: white;
margin: 0px;
}

.sidenav a {
text-decoration: none;
font-size: 18px;
display: block;
line-height: 4em;
color: white;
background-color: black;
}

.sidenav a:hover {
color: grey;
}

.sidenav .active-list {
background-color: #e2c9be;
color: black;
}
   <div id="active-buttons" class="sidenav" style="padding-top: 100px;">
<ul class="text-center">
<li>
<a href="#Profile" class="active-list">Profile</a>
</li>
<li>
<a href="#Experience">Experience</a>
</li>
<li>
<a href="#Projects">Projects</a>
</li>
<li>
<a href="#Skills">Skills</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 can I toggle two classes in two divs in pure javascript?

Use Element.classList.toggle()

var cards = document.querySelectorAll('.card')
Array.from(cards).forEach(function(card) { card.addEventListener('click', function() { Array.from(card.querySelectorAll('.back, .front')).forEach(function(el) { ['back', 'front'].forEach(function(s) { el.classList.toggle(s) }); }); });});
.card {  width: 200px;  height: 300px;  position: relative;  perspective: 1000px;  cursor: pointer;}
.front,.back { width: 100%; height: 100%; position: absolute; display: flex; justify-content: center; align-items: center; transition: 1s; backface-visibility: hidden; border-radius: 10px;}
.front { transform: rotateY(360deg);}
.back { transform: rotateY(180deg);}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div class="card">  <div class="front">Front</div>  <div class="back">Back</div></div>


Related Topics



Leave a reply



Submit