最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Get index of child elements with event listener in JavaScript - Stack Overflow

programmeradmin3浏览0评论

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(e.target);
});
<section id="slides">
  <div class="slide">1</div>
  <div class="slide">2</div>
  <div class="slide">3</div>
</section>

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(e.target);
});
<section id="slides">
  <div class="slide">1</div>
  <div class="slide">2</div>
  <div class="slide">3</div>
</section>

Share Improve this question edited Feb 17, 2019 at 21:51 Tom O. 5,9413 gold badges23 silver badges36 bronze badges asked Feb 17, 2019 at 21:41 totalnoobtotalnoob 2,74110 gold badges39 silver badges72 bronze badges 1
  • One liner: Use event delegation and then do: const idx = Array.from(e.currentTarget.children).indexOf(e.target.closest(childClass)); – aderchox Commented May 23, 2022 at 12:00
Add a ment  | 

2 Answers 2

Reset to default 9

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 e.target within it:

document.getElementById("slides").addEventListener("click", function(e) {
  const idx = [...this.children]
    .filter(el => el.className.indexOf('slide') > -1)
    .indexOf(e.target);

  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.

You can use .indexOf() and .querySelectorAll(), feeding it the list of divs and the target as arguments.

document.getElementById("slides").addEventListener("click", function(e){
  var nodes = document.querySelectorAll('#slides > .slide');
  console.log([].indexOf.call(nodes, e.target));
});
<section id="slides">
  <div class="slide">1</div>
  <div class="slide">2</div>
  <div class="slide">3</div>
</section>

发布评论

评论列表(0)

  1. 暂无评论