Halloween Sale 15% off Ends in See the plans
HTML

Turn Headings Into an Accordion

Turns every H3 inside a block with the class "wpide-accordion" into a clickable question that shows or hides the content below it, for FAQs written as plain headings and paragraphs.

Don’t have WPIDE yet? Install it on your site

Code

<style>
.wpide-accordion h3 button{all:inherit;display:flex;justify-content:space-between;align-items:center;width:100%;cursor:pointer;}
.wpide-accordion h3 button::after{content:"+";font-weight:400;margin-left:1em;}
.wpide-accordion h3 button[aria-expanded="true"]::after{content:"\2212";}
.wpide-accordion h3 button:focus-visible{outline:2px solid currentColor;outline-offset:3px;}
.wpide-accordion .wpide-accordion__panel[hidden]{display:none;}
</style>
<script>
document.querySelectorAll('.wpide-accordion').forEach(function (box, b) {
    box.querySelectorAll(':scope > h3').forEach(function (heading, i) {
        var panel = document.createElement('div');
        panel.className = 'wpide-accordion__panel';
        panel.id = 'wpide-acc-' + b + '-' + i;
        panel.hidden = true;
        while (heading.nextElementSibling && heading.nextElementSibling.tagName !== 'H3') {
            panel.appendChild(heading.nextElementSibling);
        }
        heading.insertAdjacentElement('afterend', panel);
        var button = document.createElement('button');
        button.type = 'button';
        button.setAttribute('aria-expanded', 'false');
        button.setAttribute('aria-controls', panel.id);
        while (heading.firstChild) { button.appendChild(heading.firstChild); }
        heading.appendChild(button);
        button.addEventListener('click', function () {
            var open = button.getAttribute('aria-expanded') !== 'true';
            button.setAttribute('aria-expanded', open ? 'true' : 'false');
            panel.hidden = !open;
        });
    });
});
</script>

Notes

Add wpide-accordion to a Group block containing H3 headings followed by their answers. Without JavaScript everything stays visible.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.