I want to get the index of the elements clicked in JavaScript.

Asked 2 years ago, Updated 2 years ago, 17 views

<ul>
    <li>Chocolate</li>
    <li>Vanilla</li>
    <li>Strawberry</li>
    <li> Bananas</li>
</ul>

When <li> is clicked above, I would like to get what number li is in Javascript (not jQuery).
If anyone knows how to do it, please let me know.

javascript

2022-09-29 22:15

2 Answers

You can retrieve the li array by searching for the number of matches to event.target.
Chocolate will be the 0th, so if you want it to be the 1st, please add +1 to the value you got.

function choiceItem(event){
  variable = event.target.parentNode;
  var li = ul.querySelectorAll("li");
  console.log (Array.prototype.indexOf.call(li, event.target));
}
<ul onclick="chooseItem(event)">
  <li>Chocolate</li>
  <li>Vanilla</li>
  <li>Strawberry</li>
  <li> Bananas</li>
</ul>


2022-09-29 22:15

This is a fairly simple version, but you can get the id of the list items clicked with this code.

function myFunction(event){ 
    alert(event.target.id);// If you click chocolate, item 1 is displayed.
}
<ul onclick="myFunction(event)">
    <liid="item1">Chocolate</li>
    <liid="item2">Vanilla</li>
    <liid="item3">Strawberry</li>
    <liid="item4">Banana</li>
</ul>


2022-09-29 22:15

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.