Tabs Component
JavaScript
Medium
2 views
Problem Description
You have buttons with class tab-btn and data-tab=panelId. Panels have class tab-panel and id matching data-tab. On click, show only that panel and add class active on the clicked button.
Output Format
No output (DOM change).
Constraints
Assume .tab-btn buttons and .tab-panel panels exist.
Official Solution
const btns=[...document.querySelectorAll('.tab-btn')];const panels=[...document.querySelectorAll('.tab-panel')];const show=id=>{for(const p of panels)p.style.display=(p.id===id)?'block':'none';for(const b of btns)b.classList.toggle('active',b.dataset.tab===id);};for(const b of btns)b.addEventListener('click',()=>show(b.dataset.tab));if(btns[0])show(btns[0].dataset.tab);
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!