1

I'm struggling about selecting a particular index of an element inside an array on click. Here's that peace of code and thanks in advance!

<div>

 <span class="dot"></span>
 <span class="dot"></span> -- lets say we click on this span
 <span class="dot"></span>
 <span class="dot"></span>
 <span class="dot"></span>

</div>



var dots = document.querySelectorAll(".dot");
for(var i = 0; i < dots.length; i ++){
dots[i].addEventListener("click", function(){
console.log(this) -- prints the actual html <span class="dot"></span>

// ?? How to print index of an element? To be more specific, in this case 
just "1" ??

})
}
bvlajkov
  • 13
  • 4

5 Answers5

2

Since you add an event listener to each element, you can console.log the value of i.

Note: I use let i and not var i inside the for loop because the let make i scoped to the blocked, and this preserves the current i value inside the event handler.

const dots = document.querySelectorAll(".dot");
for (let i = 0; i < dots.length; i++) {
  dots[i].addEventListener("click", function() {
    console.log({ i });
  })
}
<div>

  <span class="dot">1</span>
  <span class="dot">2</span>
  <span class="dot">3</span>
  <span class="dot">4</span>
  <span class="dot">5</span>

</div>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
2

One way to achieve this is by adding a property (I named it dotIndex) to your dots and then console.log this property.

var dots = document.querySelectorAll(".dot");

for(var i = 0; i < dots.length; i ++){
    dots[i].dotIndex = i;
    dots[i].addEventListener("click", function(){
        console.log(this.dotIndex);
    })
}

Check the fiddle: https://jsfiddle.net/254uqtm0/

However, as Ori Drori suggested, you can just change var to let in your loop and it will work. If you are confused why, check this thread: What's the difference between using "let" and "var"?

treecon
  • 2,415
  • 2
  • 14
  • 28
  • 1
    Be aware that when doing this, you’ll need to update the indexes if the number of dots change – Tanner Oct 20 '19 at 13:57
  • Thank you all guys! And special thanks to you! Custom property didn't even crossed my mind. All the best! :) – bvlajkov Oct 20 '19 at 21:31
1

Yo need only one event listener (event delegation). The handler can iterate through the existing elements and do something with the index of it. Something like:

const log = (...things) => { 
  console.clear(); 
  things.forEach(thing => console.log(thing))
};

// iterate within the handler
document.addEventListener("click", showIndex);

// alternative: add a dataset value to the elements on page load
// and make the handler do something with that. This is static and
// can't be used if the number of .dott-elements changes dynamcally
Array.from(document.querySelectorAll(".dott")).forEach( (el, i) => el.dataset.index = i);
document.addEventListener("click", alternativeShowIndex);

function showIndex(evt) {
  if (evt.target.matches(".dot")) {
    let currentDot = {};
    const allDots = Array.from(document.querySelectorAll(".dot"));
    for (let i = 0; i < allDots.length; i += 1) {
      if (allDots[i] === evt.target) {
        currentDot = {index: i, text: allDots[i].textContent};
        break;
      }
    }
    log(currentDot);
  }
}

function alternativeShowIndex(evt) {
  evt.target.matches(".dott") && log(evt.target.dataset.index);
}
<div>
 <span class="dot">first</span>
 <span class="dot">second</span>
 <span class="dot">third</span>
 <span class="dot">fourth</span>
 <span class="dot">fifth</span>
</div>

<div>
 <span class="dott">alt-first</span>
 <span class="dott">alt-second</span>
 <span class="dott">alt-third</span>
 <span class="dott">alt-fourth</span>
 <span class="dott">alt-fifth</span>
</div>
KooiInc
  • 119,216
  • 31
  • 141
  • 177
1

You can do something like this

const spans = [...document.getElementsByClassName('dot')];
spans.forEach(i => i.addEventListener('click', () => console.log(spans.indexOf(i))));
Abito Prakash
  • 4,368
  • 2
  • 13
  • 26
0

You can do like this

var dots = [...document.getElementsByClassName('dot')];

for (let i=0; i<dots.length; i++) {
 dots[i].addEventListener("click", () => {
   console.log(i);
  });
}
<div>
   <span class="dot">0</span>
   <span class="dot">1</span> 
   <span class="dot">2</span>
   <span class="dot">3</span>
   <span class="dot">4</span>
</div>
shrikantbishoye
  • 781
  • 6
  • 6