Akin Hwan
Akin Hwan

Reputation: 627

How to get the index of an element in a nodeList/HTML Collection on click

Lets say I have a NodeList resulting from var n = document.querySelectorAll('.exit') that looks like so [img.exit, img.exit, img.exit, img.exit, img.exit, img.exit]

As you can tell they are all the same element with the same className.

How would I know which element I clicked from this NodeList? Is there a way to get the index of an event target?

For example if I clicked the third element, I would like to see 2 printed out (zero-indexing).


The context of this is I am creating an application where a user can create and delete Meetings. When a user clicks on the img.exit icon I would like to delete the entire Meeting Card. But to do so I need to know which Meeting it is, which is why I would like to associate each Meeting Card with its own Meeting ID. This Meeting ID is coming from a request response. I am capable of removing the cards in the View, but to erase from my Calendar Model in the backend I need to make a DELETE request with the respective Meeting ID.

Upvotes: 0

Views: 5222

Answers (2)

beta programmers
beta programmers

Reputation: 653

A direct solution from jQuery docs (if you are using jQuery library) That makes your life simpler with DOM.

In this case, the below solutions holds good:

$(".exit").click(function() {
  // `this` is the DOM element that was clicked
  var index = $(".exit").index(this);
  alert(index);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>Click an image!</span>
<h5><img class='exit' src='sampleimage.img'>First image</h5>
<h5><img class='exit' src='sampleimage.img'>Second image</h5>
<h5><img class='exit' src='sampleimage.img'>Third image</h5>

Upvotes: -1

Rick Hitchcock
Rick Hitchcock

Reputation: 35670

Create your event listeners within a for loop, declaring the loop iterator with let instead of var.

You'll then have access to the element's index within the event handler:

var n = document.querySelectorAll('.exit');

for(let e = 0 ; e < n.length ; e++) {
  n[e].addEventListener('click', function() {
    alert(e);
  });
}
<p class="exit">Lorem</p>
<p class="exit">Ipsum</p>
<p class="exit">Hocus</p>
<p class="exit">Pocus</p>

Upvotes: 2

Related Questions