1

Ok I am really desperate now. I cant figure out how to get the index of a clicked div class in relation to the entire document.

Assuming I have a structure like this:

<div class="hello"> <div class="world">0ne</div> </div> <div class="hello"> <div class="world">Two</div> </div> <div class="container"> <div class="world">Three</div> <div class="anotherContainer"> <div class="world">Four</div> </div> </div> <div class="world">Five</div> 

How would I get the index of the second "world" class but in relation to the entire document / body. So no matter where the target is inside, I would always get the proper index.

Right now it works in relation to the parent but that is pretty much all:

https://jsfiddle.net/btkyu8wr/2/

So how could I solve this? I am trying to figure out what im missing out.

1 Answer 1

1

The simplest way seem to be using getElementsByClassName, then just iterate over them and get the index of the clicked element.

Something like this:

document.body.addEventListener("click", function(e) { if(e.target != e.currentTarget) { var className = e.target.className; var els = document.getElementsByClassName(className); for(var i = 0; i < els.length; i++) { if(els[i] == e.target){ alert(i+1); return i+1; } } } });
<div class="hello"> <div class="world">0ne</div> </div> <div class="hello"> <div class="world">Two</div> </div> <div class="container"> <div class="world">Three</div> <div class="anotherContainer"> <div class="world">Four</div> </div> </div> <div class="world">Five</div>

Note that I'm doing i+1, meaning I'm returning one-based indexes. Of course, if you want them to be zero-based, just use i.

Sign up to request clarification or add additional context in comments.

2 Comments

Holy carp. Why didnt I think about this xD. My mind was so consumed into the slice.call / indexOf solution that I didnt open myself to other possibilities. Thank you so much, this is a great and clean answer : )
Haha, I know the feeling, sometimes a fresh set of eyes can point out how simple a solution is. :) You're welcome!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.