How to get particular index by click event in js | Sololearn: Learn to code for FREE!


How to get particular index by click event in js

I am confused to get index by click event <ul class="list"> <li>a</li> <li>b</li> </ul> If we get document.getElementsByClassName("list"); It will return an array so I want to get a particular index of an element like first tag li tag index is 0 2nd li tag index is 1

4/30/2021 6:47:34 PM

Shubham Singh Bhadauriya

5 Answers

New Answer


Is this what you mean?


What does index mean here? did you mean to get the text in one <li> element one at a time? Which element should trigger this on click event?


document.getElementsByClassName("list"); will return a collection of all element references having "list" as class name, or undefined in case no element was found to match the class name filter. I see in the code <ul class="list">. So document.getElementsByClassName("list") will (on success) return a collection of <ul> element references, rather than a collection of <li> elements. Anyways, which element is to be clicked to trigger the behaviour? a <button>? or something else?



When we click on any li tag it should return their appropriate index