i want use the same code for multiple modules in this page and i already tried some different method but nothing seem to be working. i don’t want to duplicate the existing codes infinitely,
document.addEventListener('DOMContentLoaded', function () {
const arrowDown = document.getElementById('arrow-down');
const contentContainer = document.getElementById('content-container');
arrowDown.addEventListener('click', function () {
const content = document.getElementById('content');
if (contentContainer.style.maxHeight) {
contentContainer.style.maxHeight = null;
arrowDown.style.transform = 'rotate(0deg)';
} else {
contentContainer.style.maxHeight = content.scrollHeight + 'px';
arrowDown.style.transform = 'rotate(180deg)';
}
});
});
#content-container {
overflow: hidden;
max-height: 0;
transition: max-height 0.3s ease-out;
}
#content {
padding: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
#arrow-down {
cursor: pointer;
font-size: 24px;
transition: transform 0.3s ease-out;
}
<div class="module-sub container">
<div class=" d-flex justify-content-between">
<div class="module-heading">
EXCEL
</div>
<div id="arrow-down" class="module-arrow">▼</div>
</div>
<div id="content-container">
<div id="content" class="mod-content">
<ul>
<li>Excel Basics</li>
<li>Excel Essentials</li>
<li>Formulae</li>
<li> Data Analysis</li>
<li>Charts</li>
<li>Pivot Tables</li>
<li>Lookup</li>
</ul>
</div>
</div>
</div>
I tried using for loops and classes but nothing worked the animation and content reveal didn’t work
2
Answers
You need to use class names instead of ID’s for the most part. Once you do that, just loop over the outer elements, and then within that loop you can find the inner elements.
What I mean is when you use
document.getElementBy*
functions, you can provide a different starting point thandocument
. If you only want it to find certain elements inside of a given element you can usemyElement.getElementBy*
Here’s a working example. I switched everything to CSS classes, and I’m using
querySelectorAll
andquerySelector
beause I find that simpler to work with.By adding an event listener to each element with the ID "arrow-down", looping through each item with that ID, and then toggling a max-height property on the elements with the ID "content-container". This allows multiple elements to be toggled on and off on a webpage without the use of classes.