[Solved] Select an element with Javascript [duplicate]


You can use .querySelectorAll() to select all div elements with an id, iterate NodeList of div elements, attach click handler within a loop

<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<div id="4"></div>
<div id="5"></div><br>
<div id="6"></div>
<div id="7"></div>
<div id="8"></div>
<div id="9"></div>
<div id="10"></div><br>
<div id="11"></div>
<div id="12"></div>
<div id="13"></div>
<div id="14"></div>
<div id="15"></div><br>
<div id="16"></div>
<div id="17"></div>
<div id="18"></div>
<div id="19"></div>
<div id="20"></div><br>
<div id="21"></div>
<div id="22"></div>
<div id="23"></div>
<div id="24"></div>
<div id="25"></div><br>

<script>
  let divs = document.querySelectorAll("div[id]");
  for (let div of divs) {
    div.textContent = div.id;
    div.addEventListener("click", displayDate);
  }

  function displayDate() {
    this.style.backgroundColor="red";
  }
</script>

1

solved Select an element with Javascript [duplicate]