Using function parameters to handle HTML tags (Javascript)

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:

        <div id="section 1">
         <div id="section 2" style="display: none;">
         <div id="section 3" style="display: none;">

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!

Can you give them all a Class? (they don’t need any style)

Then you could use the document.getElementsByClassName() selector to grab all of them & loop through the result with something similar to you have suggested.

Edit: and your description/topic is perfect! Sample code, identify the problem, what you want as a result and your thoughts on the solution :+1:

1 Like

Thank you very much for your help :smile:
I wanted to be as clear as possible since I wasn’t sure if what I was thinking would make sense.

Changing the ideas to a single class makes sense, but I’m still not sure how to handle them inside the function. If I call them, do I need to insert them into an array and then pass them through a for loop, or is there a way to do that automatically?

Thank you again for your help!

1 Like

Actually, I just realized I also wouldn’t know how to save each instance separately since they all have the same class. I can imagine being able to make all of them visible or invisible at the same time, but since I need one of them visible, I’m not sure how to make that work with a class.

The document.getElementsByClassName() will create a Nodelist like an Array. Then you can loop through that.

The class doesn’t actually do anything visibly, it’s just let’s you select them all as a group.

Here’s a quick pen for example.

1 Like

Thank you very much, this makes a lot more sense!

1 Like