Design comparison
Solution retrospective
Iād like to get an opinion on the Toggle functionality in JavaScript
const btnsToggle = document.querySelectorAll('.toggle-accordion-item');
btnsToggle.forEach(item => {
item.addEventListener('click', (event) => {
let childNode = event.target;
let parentNode = childNode.parentElement;
let icon = parentNode.childNodes.item(3)
let content_text = parentNode.nextElementSibling
if(content_text.classList[0]=='accordion-text-answer') {
content_text.toggleAttribute('hidden')
icon.classList.toggle('icon-minus')
}
})
})
Community feedback
- @alex931dPosted 9 months ago
Hello! Great project overall. Here's a refactored version of your code that uses data-* attributes. Typically, using data-* over classes in JavaScript helps separate the frontend from the logic. This is especially useful when working as a backend developer, as you wouldn't want your logic to break due to a single class. :)
const accordionContainer = document.querySelector('.accordion-container'); accordionContainer.addEventListener('click', (event) => { if (event.target.dataset.toggle === 'accordion-item') { let button = event.target; let parentNode = button.parentElement; let answerContent = parentNode.querySelector('[data-answer="true"]'); let icon = parentNode.querySelector('[data-icon="true"]');
if (answerContent) { answerContent.toggleAttribute('hidden'); icon && icon.classList.toggle('icon-minus'); } }
}); quick note this might not work out of the box since you would need modify your current code
Marked as helpful0
Please log in to post a comment
Log in with GitHubJoin our Discord community
Join thousands of Frontend Mentor community members taking the challenges, sharing resources, helping each other, and chatting about all things front-end!
Join our Discord