How can I get the Index of an Element with JavaScript?

0

How can I get the index of an element when I click on it?

<p>Parrafo 1</p>
<p>Parrafo 2</p>
<p>Parrafo 3</p>
<p>Parrafo 4</p>
<p>Parrafo 5</p>

var p = document.querySelectorAll('p');

for(var i = 0; i < p.length; i++)
{
  p[i].addEventListener('click', funcion_uno);
}

funcion_uno()
{
  console.log('el index del elemento clickeado es: '...);
}
    
asked by brian 27.02.2018 в 18:47
source

1 answer

2

Based on your example, you get all the elements with tag p and you assign a function onclick with the index:

document.querySelectorAll("p").forEach((element, index) => {
    element.onclick = () => alert(index)
});
    
answered by 27.02.2018 / 19:21
source