Skip to content Skip to sidebar Skip to footer

What Can I Get Number Of Clicked Element

I have a few elements with identical class names. How can I get the number of the elements which I clicked with onclick events? For example: var x = document.getElementsByClassName

Solution 1:

You can use indexOf on an array of document.getElementsByClassName("myclass"). You can use Array.from or [].slice.call to make the array.

Assuming your click handlers look like in the snippet below and they “Do something to e.target where e.target is the element that has been clicked, you can check the indexOfe.target on the array like this:

document.addEventListener("click", function(e) {
  if (e.target.classList.contains("myclass")) {
    /*
      The above part could as well look like
      div1.onclick = function(e){…};
      div2.onclick = function(e){…};
      …
    */console.log("Do something to %o", e.target);
    console.log("Index of clicked element: %d", Array.from(document.getElementsByClassName("myclass")).indexOf(e.target));
  }
});
<div><divclass="myclass">A0</div><div>B1</div><divclass="myclass">A2</div></div><div><div>B3</div><divclass="myclass">A4</div></div><divclass="myclass">A5</div><divclass="myclass">A6</div><div>B7</div><divclass="myclass">A8</div>

If you want the index of the element within the same parent element, you can instead use:

Array.from(e.target.parentNode.children).indexOf(e.target)

If you want to restrict the above to elements with the myclass class, you can use something like:

Array.from(e.target.parentNode.getElementsByClassName("myclass")).indexOf(e.target)

Or for direct children:

Array.from(e.target.parentNode.children).filter(function(elem){
  return elem.classList.contains("myclass");
}).indexOf(e.target)

Solution 2:

You can capture info about the clicked element in the onClick event handler.

Whatever function runs when he click event happens will be passed an event as the first parameter. That event object has a target which will be a reference to the specific element that was clicked.

function clickHandler(event) {
   console.log(event.target);
}

Post a Comment for "What Can I Get Number Of Clicked Element"