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>
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);
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.
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With