Search code examples
javascriptweb-frontend

How to loop event click the get the attributes of each a?


I want to get the value of the data-id of each a property of the onclick click event, but the click does not respond and does not get the value of each property. Do you have any way to click on each attribute?

Please take a look at my code:

window.onload = function() {
  var showClick = document.getElementById("showClick");
  for (var i = 0; i < showClick.length; i++) {
    (function(i) {
      showClick[i].onclick = function(event) {
        event.preventdefault()
        alert(showClick.getAttribute("data-id"));
      }
    })(i);
  }
}
<ul>
  <li>
    <a id="showClick" href="" data-id="1">dd</a>
  </li>
  <li>
    <a id="showClick" href="" data-id="2">ee</a>
  </li>
  <li>
    <a id="showClick" href="" data-id="3">gg</a>
  </li>
  <li>
    <a id="showClick" href="" data-id="4">xx</a>
  </li>
</ul>


Solution

  • First fo all the id attribute must be unique. Use common classes instead like :

    <li>
        <a class="showClick" href="" data-id="1">dd</a>
    </li>
    <li>
        <a class="showClick" href="" data-id="2">ee</a>
    </li>
    

    It will be better to use .addEventListener() to attach the click event.

    NOTE: It's more efficient to use dataset when you deal with data-* attributes like :

    this.dataset.id
    

    To get the data-id attribute.

    window.onload = function() {
      var showClick = document.querySelectorAll(".showClick");
    
      for (var i = 0; i < showClick.length; i++) {
        showClick[i].addEventListener('click', function(event) {
          event.preventDefault();
    
          console.log(this.dataset.id);
        });
      }
    }
    <ul>
      <li>
        <a class="showClick" href="" data-id="1">dd</a>
      </li>
      <li>
        <a class="showClick" href="" data-id="2">ee</a>
      </li>
      <li>
        <a class="showClick" href="" data-id="3">gg</a>
      </li>
      <li>
        <a class="showClick" href="" data-id="4">xx</a>
      </li>
    </ul>