I’m working on a website at work, and I want to use “display: none” and “getElementById” to create a page that only displays one section at a time, but has buttons to change which section is visible at any given time.
The below code is not the actual code (for confidentiality reasons), but is a simple recreation of the code:
<main>
<div id="section 1">
<ul>
<li>Apple</li>
<li>Orange</li>
<li>Banana</li>
</ul>
</div>
<div id="section 2" style="display: none;">
<ul>
<li>Broccoli</li>
<li>Carrot</li>
<li>Onion</li>
</ul>
</div>
<div id="section 3" style="display: none;">
<ul>
<li>Bread</li>
<li>Rice</li>
<li>Cereal</li>
</ul>
</div>
</main>
For clarity, I’ve included the “display: none” style in the HTML tag, but in reality I’m using an external style sheet.
My question is this: is there a way use “getElementById” and function parameters in such a way that all of the sections can be handled with a single function? I know that I could write three different functions and hard code each section, but that seems inefficient, and I’m assuming there’s a way to pass all three sections into the same function using parameters.
If I had to take a guess at how the function would work, I would say it would look something like this:
function changeDisplay(???) {
if (getElementById(???) !== this.getElementById(???)) {
document.getElementById(???).style.display = none;
} else {
document.getElementById(???).style.display = block;
}
I apologize for the long description; if anyone has any suggestions on how to write this code, I would appreciate it. Thanks!