Going from id to class name to execute a function

When I use an id for a button, which sends one to the top of the page, then this script works to execute it:

const btnReturnToTop = document.getElementById("returnToTop");
function returnToTop(){
btnReturnToTop.addEventListener('click', returnToTop);

But if I scatter several of these buttons down a long page, I need to use a class, not an id. Then I’m stuck. Using getElementsByClassName in place of getElementById won’t work because the former returns an array, not a specific button pressed.

What scripting do you use to deal with multiple buttons that need to run the same script? I could make every button a different id and duplicate the function to deal with each id, but I’m sure JavaScript has a more elegant way.


Don’t do that :slight_smile:

You can give each button a class name:

<button class="myClass">Button 1</button>
<button class="myClass">Button 2</button>
<button class="myClass">Button 3</button>

Then run the function on click:

const buttons = document.querySelectorAll('.myClass');

function myFunction() {

buttons.forEach((button) => {
  button.addEventListener('click', myFunction);

Event delegation is also an option:

<div id="myDiv">
  <button>Button 1</button>
  <button>Button 2</button>
  <button>Button 3</button>

As are anonymous functions:

const myDiv = document.querySelector('#myDiv');

myDiv.addEventListener('click', (e) => {
  if (e.target.matches('button')) {

Multiple ways to accomplish the same thing.



OK, I’m trying this out. I have:

<input type="button" value="Top" class="buttonSetup toTop returnToTopC">

and the external script:

const buttons = document.querySelectorAll('.returnToTopC');
function returnToTopC() {
buttons.forEach((button) => {
  button.addEventListener('click', returnToTopC);

I’m not getting any errors in the console, yet the buttons don’t take me anywhere. Maybe because they are “input” buttons, there should be a difference there.

Okay, let’s check for easy solutions first.

  • Is the external script being loaded by the page?
  • Does the script run?
  • Are console,log statements in the function seen in the browser console?

Those are good first checks to do before we delve into the plumbing of how the functions and events are connected.

1 Like

I know it works because another script linked to that external page is working (removing it nullifies it).

I moved the script to the top of the external page…and the buttons work!

(Now to figure out why my goToHome button on the same external page is not working, though I’ve moved it around, too.)

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.