<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.
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>
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>
© 2024 OneMinuteCode. All rights reserved.