javascript - Trouble getting the index of a child when it is clicked -
i'm trying index of child within parent element. followed answer here, ended infinite loop.
my code 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 output 0 when user clicks on first span because it's first child in "spans" id:
<div id="spans"> <span>this span #1</span> <span>this span #2</span> <span>this span #3</span> </div>
any appreciated.
as not changing span
variable in loop, condition same. if assign previous sibling variable, 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 span #1</span> <span>this span #2</span> <span>this span #3</span> </div>
Comments
Post a Comment