Asperger
Asperger

Reputation: 3222

Getting index of clicked element in relation to the entire document

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.

Upvotes: 1

Views: 189

Answers (1)

Shomz
Shomz

Reputation: 37701

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.

Upvotes: 1

Related Questions