1. HTML Structure
Ensure your HTML structure for each accordion section includes the summary and details tags, and that there is a place for the icons:
2. CSS to Hide Existing Caret Icons
Add CSS to hide any existing caret icons within the summary:
/* Hide the default caret SVG within the summary */
.product__accordion details summary .icon-caret {
display: none;
}
3. JavaScript to Manage Accordion State and Icons
Ensure your JavaScript handles the toggle of the plus/minus icons and manages opening and closing of the accordions:
// Define SVG icons
const plusIcon = <svg class="plus-icon" width="24px" height="24px" viewBox="0 0 24 24" fill="none" xmlns="[http://www.w3.org/2000/svg](http://www.w3.org/2000/svg)"> <path d="M6 12H18M12 6V18" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path> </svg>;
const minusIcon = <svg class="minus-icon" width="24px" height="24px" viewBox="0 0 24 24" fill="none" xmlns="[http://www.w3.org/2000/svg](http://www.w3.org/2000/svg)"> <path d="M5 12H19" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path> </svg>;
document.querySelectorAll(‘.product__accordion details’).forEach((accordion) => {
const summary = accordion.querySelector(‘summary’);
const titleDiv = summary.querySelector(‘.summary__title’);
// Add plus icon initially to all closed accordions
if (!accordion.hasAttribute(‘open’)) {
titleDiv.innerHTML += plusIcon;
} else {
titleDiv.innerHTML += minusIcon;
}
accordion.addEventListener(‘click’, function(event) {
// Prevent default behavior to properly handle the state
event.preventDefault();
document.querySelectorAll(‘.product__accordion details’).forEach((otherAccordion) => {
if (otherAccordion !== accordion) {
otherAccordion.removeAttribute(‘open’);
// Replace minus icon with plus icon for other accordions
const otherSummary = otherAccordion.querySelector(‘summary’);
const existingMinusSvg = otherSummary.querySelector(‘.minus-icon’);
if (existingMinusSvg) {
existingMinusSvg.remove();
otherSummary.querySelector(‘.summary__title’).innerHTML += plusIcon;
}
}
});
// Toggle the current accordion
const isOpen = !accordion.hasAttribute(‘open’);
const svgIcon = summary.querySelector(‘.plus-icon, .minus-icon’);
if (svgIcon) {
svgIcon.remove();
}
if (isOpen) {
accordion.setAttribute(‘open’, ‘’);
summary.querySelector(‘.summary__title’).innerHTML += minusIcon;
} else {
accordion.removeAttribute(‘open’);
summary.querySelector(‘.summary__title’).innerHTML += plusIcon;
}
});
});
If this solution works for you, please consider accepting it as a solution so that it can help others in the community as well. If you have any questions or need further assistance, feel free to ask. Happy coding!