1

I'm trying to get the index of a child within a parent element. I followed the answer here, but ended up with an infinite loop.

My code so far:

var div = document.getElementById("spans");
var spans = div.getElementsByTagName("span");

div.addEventListener('click', function(e) {
    var span = e.target;
    var spanSiblings = 0;

    while((span.previousElementSibling) != null ) {
        spanSiblings++;
    }

    console.log(spanSiblings);
});

The aim is to output 0 when the user clicks on the first span because it's the first child in the "spans" id:

<div id="spans">
    <span>This is span #1</span>
    <span>This is span #2</span>
    <span>This is span #3</span>
</div>

Any help would be appreciated.

Community
  • 1
  • 1

3 Answers3

2

Borrowing a little from jQuery, which checks the elements position with $.inArray in it's index function, you can do

var div = document.getElementById("spans");
var spans = div.getElementsByTagName("span");

div.addEventListener('click', function(e) {
    var span  = e.target;
    var arr   = [].slice.call(spans);
    var index = arr.indexOf( span );

    console.log( index );
});

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
1

As you are not changing the span variable in the loop, the condition will always be the same. If you assign the previous sibling to the variable, then it works:

var div = document.getElementById("spans");
var spans = div.getElementsByTagName("span");

div.addEventListener('click', function(e) {
    var span = e.target;
    var spanSiblings = 0;

    while((span = span.previousElementSibling) != null ) {
        spanSiblings++;
    }

    console.log(spanSiblings);
});
<div id="spans">
    <span>This is span #1</span>
    <span>This is span #2</span>
    <span>This is span #3</span>
</div>
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

You have to modify your while loop condition. You don't have any condition to terminate the while loop. Change your while loop code to

while((span = span.previousElementSibling) != null ) {
    spanSiblings++;
}
u4865787
  • 11
  • 1