Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'}; } 

this.index?

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

<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Untitled Document</title> <style type="text/css"> body{margin:0;} #container div{height:50px;line-height:50px; text-align:center} </style> </head> <body> <div id="container"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> <div>6</div> </div> <script> for (i = 0; i < document.getElementById('container').children.length; i++) {     document.getElementById('container').children[i].onclick = function(){alert('Number ' + i + ' was clicked')}; } </script> </body> </html> 
like image 946
Hakan Avatar asked Jan 10 '12 10:01

Hakan


People also ask

How do I get the index of a clicked element?

index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements. Pass the selector to the index(selector) . $(this). index(selector);

How do you find the index of an element in HTML?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found. The following illustrates the syntax of the indexOf() method.


2 Answers

Here is a piece of code that can help you get the index of the clicked element inside the for loop. All you need is a new scope:

var g = document.getElementById('my_div'); for (var i = 0, len = g.children.length; i < len; i++) {      (function(index){         g.children[i].onclick = function(){               alert(index)  ;         }         })(i);  } 

Edit 1: Incorporating user Felix Kling's comments into the answer.

event handler already is a closure

Edit 2: Updated fiddle link

like image 26
Ashwin Krishnamurthy Avatar answered Oct 07 '22 14:10

Ashwin Krishnamurthy


With ES6 destructuring you can do

const index = [...el.parentElement.children].indexOf(el) 

or

const index = Array.from(el.parentElement.children).indexOf(el) 

or ES5 version

var index = Array.prototype.slice.call(el.parentElement.children).indexOf(el) 
like image 105
MelkorNemesis Avatar answered Oct 07 '22 14:10

MelkorNemesis