Accordion Toggle
JavaScript
Medium
4 views
Problem Description
You have sections .acc where each has a header .acc-head and body .acc-body. On clicking header, toggle its body. Close other bodies in the same container.
Output Format
No output (DOM change).
Constraints
Assume each .acc contains .acc-head and .acc-body.
Official Solution
document.querySelectorAll('.acc').forEach(root=>{const head=root.querySelector('.acc-head');const body=root.querySelector('.acc-body');if(!head||!body)return;head.addEventListener('click',()=>{document.querySelectorAll('.acc .acc-body').forEach(b=>{if(b!==body)b.style.display='none';});body.style.display=(body.style.display==='none'||!body.style.display)?'block':'none';});});
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!