Liam
Liam

Reputation: 111

How to get index position of clicked element in javascript

I am trying to get the index value of a particular element that is clicked on from a for loop array. What i would like to do is then use this index value and pass it to a variable called indexValue which will then determine a specific div to show. The div it will show will be the one with the same index value that was passed to the variable. I hope this makes sense, I am just not to sure how to achieve this?

The markup would be something like this

HTML

<div class="button"></div>
<div class="button"></div>
<div class="button"></div>
<div class="button"></div>

CSS

.test {
   display: none;
}

.show {
   display: block;
}

JS

var button = document.querySelectorAll('.button');
for (var i = 0; i < button.length; i++) {
    button[i].addEventListener('click', function () {

    var indexValue: //Get index value from clicked element
    var test = document.querySelectorAll('.test');

    test[indexValue].classlist.add('show');

  }
}

Upvotes: 0

Views: 5321

Answers (1)

Eric Yang
Eric Yang

Reputation: 2750

You can put your eventListener in a closure that takes a parameter from your loop. The alert is only so that when you click it in the fiddle you can see the result of the index

var button = document.querySelectorAll('.button');
for (var i = 0; i < button.length; i++) {    
    button[i].addEventListener('click', ((j) => {         
    return function() {
      alert(j)
    }
  })(i))
}

http://jsfiddle.net/cbpw61ur/20/

Upvotes: 3

Related Questions