I've been trying to create tabs in JavaScript. When clicking on a new tab the active class should be applied to it as well as its associated panel content should be displayed. However, the active class isn't being applied when another tab is clicked and the panels are not changing either, they are just stacking on top of each other.
const tabs = document.querySelector(".tabs");
const active = document.querySelector(".active");
const panel = document.querySelector(".panel");
function onTabClick(event) {
// deactivate existing active tabs and panel
active.classList.remove('.active');
for (let i = 0; i < panel.length; i++) {
panel[i].style.display = "none";
}
// activate new tabs and panel
event.target.classList.add('.active');
let classString = event.target.innerHTML;
console.log(classString);
document.getElementsByClassName(classString)[0].style.display = "block";
}
tabs.addEventListener('click', onTabClick, false);
.tabs {
display: flex;
justify-content: space-around;
margin: 20px 2px 40px 2px;
height: 40px;
box-shadow: 0 0 1px 1px rgba(0, 0, 0, 0.2);
}
.tabs>* {
width: 100%;
color: dimgray;
height: 100%;
cursor: pointer;
display: flex;
justify-content: center;
align-items: center;
}
.tabs>*:hover:not(.active) {
background-color: rgb(220, 220, 220);
}
.tabs>.active {
color: white;
background-color: #4CAF50;
}
.panel {
display: none;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div class="tabs">
<div class="tab active">List</div>
<div class="tab">Grid</div>
<div class="tab">something</div>
</div>
<div class="Lists panel" style='display:block'>
panel 1 text
</div>
<div class="Grid panel">
panel 2 text
</div>
<div class="something panel">
panel 3 text
</div>
</body>
</html>