hi guys i have this code s of tabbed component that most of you familiar with . the problem is that when i click on certain tab i want to other tabs get hidden
const tab = document.querySelectorAll(".tab");
const tabContainer = document.querySelector(".upContainer");
tabContainer.addEventListener("click", function(e) {
const clicked = e.target.closest(".tab").textContent;
document
.querySelector(`.content__${clicked}`)
.classList.remove("hidden");
});
.container {
display: flex;
flex-direction: column;
width: 100%;
height: 100vh;
align-items: center;
justify-content: center;
}
.upContainer {
display: flex;
}
.tab {
width: 100px;
height: 70px;
background-color: aqua;
cursor: pointer;
text-align: center;
margin: 0px 10px;
}
.content {
width: 300px;
height: 100px;
margin-top: 10px;
text-align: center;
background-color: black;
color: aliceblue;
}
.hidden {
display: none;
}
<div class="container">
<div class="upContainer">
<div class="tab1 tab">tab1</div>
<div class="tab2 tab">tab2</div>
<div class="tab3 tab">tab3</div>
</div>
<div class="downContainer">
<div class="content__tab1 content">content1</div>
<div class="content__tab2 content hidden">content2</div>
<div class="content__tab3 content hidden">content3</div>
</div>
</div>
3
Answers
Consider toggling the other tab content containers’ back to hidden when you change the active one to be shown.
Here’s a CSS-only solution (mostly for reference, since JS is preferred):
You have multiple
.content
elements and you only want one of them to be shown at a time. This is exactly the same as how radio buttons work: One checked at a time.Using that, we can add some
<label>
s and<input type="radio">
s:For further explanation, see this answer.
Try it:
Assuming that you mean you only want the content associated with a tab to be shown (and all the other tab content hidden) – you can iterate over the
content
elements andtoggle
thehidden
class on/off depending on whether it matches a condition.Using data attributes to store the ids rather than classes may make the process easier to code/understand.
Additional documentation
matches
Destructuring assignment