1

Here, I have parent div of class = "alphabets" and have child div's all with same class = "word"

<div class="alphabets">
  <div class="word"> abc </div> //1st child
  <div class="word"> def </div> //2nd child
  <div class="word"> ghi </div> //3rd child
  <div class="word"> jkl </div> //4th child
  <div class="word"> mno </div> //5th child
</div>

what I need is When I clicked on 'jkl'. fun() should return its index i.e whether it is 1st child or 2ndchild or 6th child...

1 Answers1

0

You can use indexOf on the children (after converting it to an array) of the parent element.

document.querySelector('.alphabets').addEventListener('click', function(e){
  if (e.target.matches('.word')) console.log([...this.children].indexOf(e.target));
});
<div class="alphabets">
  <div class="word"> abc (1st child)</div>
  <div class="word"> def (2nd child)</div>
  <div class="word"> ghi (3rd child)</div>
  <div class="word"> jkl (4th child)</div>
  <div class="word"> mno (5th child)</div>
</div>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80