skip to Main Content

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)
       })

2

Answers


  1. 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)
    }));
    
    Login or Signup to reply.
  2. If you really want to stick on this plan:

    The statement getElementById("top1, top 2, top3") will fetch the element with id top1, top 2, top3, which, i suppose doesn’t exist.

    You should take each element as getElementById("top1"), getElementById("top2"), …

    I’d use a loop until getElementById("topX") will return null (meaning that was last element declared with this kind of id).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search