Reputation: 3518
I am trying to create a simple tabbed feature using js and css.
When a tab button is clicked, it should remove all active
classes from the control and then add the active
class to only the selected elements.
However, when I try to remove the active
class, it does not work as expected.
Switching between tabs should only allow one button and one content to be active at any time.
See this jsFiddle
var tabs = document.getElementsByClassName('tabs');
Array.prototype.forEach.call(tabs, function(tab) {
var btns = tab.getElementsByClassName('tabs-button');
Array.prototype.forEach.call(btns, function(btn) {
btn.addEventListener('click', function(e){
e.preventDefault();
var href = this.getAttribute('href').replace('#','');
var target = document.getElementById(href);
var allActive = tab.getElementsByClassName('active');
Array.prototype.forEach.call(allActive, function(active) {
active.classList.remove('active');
});
this.classList.add('active');
target.classList.add('active');
});
});
});
Can anyone see where I am going wrong?
Upvotes: 1
Views: 5696
Reputation: 11
The easiest method that I've discovered and it works perfectly is using: -someElementToRemoveClassName-.classList.value = ""
It clears off the entire ClassName List and returns it to original state, letting ya guys to re-add the transition class again and makes the transition reappear again as usual.
Upvotes: 0
Reputation: 413717
The return value from getElementsByClassName()
is a live node list. That it's "live" means that it changes automatically when the DOM changes.
Your loop is removing the class "active" from the elements of the list. As soon as that happens, element by element, each element vanishes from the node list, as if it had never been there. The list is thus one element shorter. The .forEach()
loop does its work by iterating over the numeric indexes, and it'll always increment. Thus, you end up skipping entries.
The best way to do that is to just keep changing the first element of the list until the list is empty:
var allActive = tab.getElementsByClassName('active');
while (allActive.length) {
allActive[0].classList.remove("active");
}
Upvotes: 6