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.