I have to use my script with document.getElementById("") multiple times

40 Views Asked by At

I'm making a layout where each box has to use a... id="top1", id="top2", id="top3", etc... so that when you click it goes to the top of the document, but I can't find a way to make that happen, whow can I use only one function to do this without repeat it multiple times? I would be very grateful to hear a solution, thanks in advance

I Try to do something like this so that clicking on each box makes the document scroll to the top:

const top1 = document.getElementById("top1, top 2, top3")
   top1.addEventListener('click', () => {
         window.scrollTo(0, 0)
       })
1

There are 1 best solutions below

2
Barmar On

document.getElememtById() can only search for a single ID at a time.

Don't use different IDs. Give them all class="top", then you can get them all with document.querySelectorAll(".top"), and loop over this result.

document.querySelectorAll(".top").forEach(top => top1.addEventListener('click', () => {
  window.scrollTo(0, 0)
}));