Answer the question
In order to leave comments, you need to log in
How to get the number of an element in an array on click?
Good time of the day!
Comrade, tell me where to dig. I'm just starting to learn javascript and I ran into a problem:
There is a table in html, there is an array of td elements (100 pieces in the array).
When you click on td, you need to find out the number of this element in the array.
Tried like this:
for (var i = 0; i < fieldArray.length; i++) {
fieldArray[i].onclick = check;
}
Here I use a loop to hang a click event on all elements, then I tried to write this function that finds out the number of the element in the array (I can’t give examples of incorrect code now, but I tried a lot). There is not enough knowledge to implement this miracle, tell me how to do it or where to dig / what to read. Thank you!
Answer the question
In order to leave comments, you need to log in
var cellsArray = [ ...document.querySelectorAll('td') ];
var listener = e => document.getElementById('output').innerHTML = cellsArray.indexOf(e.target); // Создать элемент вывода надо заранее
cellsArray.forEach( cell => cell.addEventListener( 'click', listener ) );
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question