Hakan Hakan - 4 months ago 33
Javascript Question

Get index of clicked element using pure javascript

I need to know the index of clicked element. Can't figure out how to do it

for (i = 0; i < document.getElementById('my_div').children.length; i++) {
document.getElementById('my_div').children[i].onclick = function(){'ALERT POSITION OF CLICKED CHILD'};


here is a example of what I am trying to do (it only gives back 6):

<!DOCTYPE html>
<meta charset="utf-8" />
<title>Untitled Document</title>
<style type="text/css">
#container div{height:50px;line-height:50px; text-align:center}
<div id="container">
for (i = 0; i < document.getElementById('container').children.length; i++) {
document.getElementById('container').children[i].onclick = function(){alert('Number ' + i + ' was clicked')};


Check this out.

Basically Your JS should have a closure,

  var g = document.getElementById('my_div');
for (var i = 0, len = g.children.length; i < len; i++)

        g.children[i].onclick = function(){
              alert(index)  ;