Does defining order of event listeners matter?

i have this express app built with nodejs and mongoDB my event listeners linked to this are acting wierd.
This is my main.js file

const threemonth=document.getElementById("threemonth");
const sixmonth=document.getElementById("sixmonth");
const onemonth=document.getElementById("onemonth");
const buy1=document.getElementById("buy1");
const buy3=document.getElementById("buy3");
const buy6=document.getElementById("buy6");
const test=document.getElementById("test");

threemonth.addEventListener("click",function(){
  buy3.classList.remove("displaymonth");
  buy1.classList.add("displaymonth");
  buy6.classList.add("displaymonth");
})

sixmonth.addEventListener("click",function(){
  buy6.classList.remove("displaymonth");
  buy3.classList.add("displaymonth");
  buy1.classList.add("displaymonth");
})

onemonth.addEventListener("click",function(){
  buy1.classList.remove("displaymonth");
  buy6.classList.add("displaymonth");
  buy3.classList.add("displaymonth");
})

test.addEventListener("click",function(){
  alert("you have clicked");
})

The problem is the event listener for “test” oly works when it is defined on the top,before all other listeners .But then the listeners below the “test” listeners doesnt work.If i define “test” listener at the bottom .All other listeners work except “test” listeners.What is the solution here please help me out

and to mention the only event listener which is in a separate,different page is “test” all other listeners are in the same page

Without seeing the full code it is hard to help.

How are the elements you are attaching the listeners to, added to the page?

Are you using the same js file on two pages with different elements on them? If so it sounds like you are likely getting an error and depending on the order of the listeners and the page you are on it will affect the listeners differently.

The page with the 6 elements will error if you ask it to look for the test element. So if the test listener is in front of the others listeners they never run because the script errors out. And vice versa.

i am using the same js file on every pages …ya i did notice what you are telling .in my home page there is a error in console telling threemonth not defined .After i navigate to the page in which the element with id “threemonth” the error goes away and lists a new error telling “test” is not defined.And then when i navigate to the page where the element with the id test is present the error goes away

Yep, you can’t do that.

How to best fix it really depends on the app but sharing DOM manipulation code across pages with different elements requires a different approach. You can try using a common parent element like the document and do event delegation instead.