Get index of child elements with event listener in JavaScript

  • A+

Without changing the HTML, how can I get the index of each slide container when clicked on?

eg. they clicked on 2, how do I get a value such as node[1]?

document.getElementById("slides").addEventListener("click", function(e){  console.log(; });
<section id="slides">   <div class="slide">1</div>   <div class="slide">2</div>   <div class="slide">3</div> </section>


As long as you're not using arrow function syntax in your callback you can use this to reference the slides element. Using ES6 spread syntax, you can spread its child elements into an array and then use indexOf on that array to get the index of within it:

document.getElementById("slides").addEventListener("click", function(e) {   const idx = [...this.children]     .filter(el => el.className.indexOf('slide') > -1)     .indexOf(;    if (idx > -1) {     console.log(`Slide index: ${idx}`);   } });
<section id="slides">   <div class="slide">1</div>   <div class="slide">2</div>   <span>Not a slide</span>   <div class="slide">3</div> </section>

Updated: I updated my answer to include only elements having the class slide by implementing the filter method - without this, the index could be thrown off by sibling elements that are not slides.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: