I have a ul
with a number of li's
which contain an img
tag and a p tag in them and I am trying to find the index of the li
on click like so :
$("li").on("click", (e) => {
console.log($(e.target).parent().index());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>
<img src="">
<p>Hindu</p>
</li>
<li>
<img src="">
<p>Muslim</p>
</li>
<li>
<img src="">
<p>Christian</p>
</li>
</ul>
But I get odd numbers when I click, I’ve check the function and it is selecting the li
.
I tried selecting the parent li
and logging it’s index but I get incorrect indexes.
2
Answers
The target isn’t always what you think it is. Sometimes it’s the list item, so the index will refer to that.
Sometimes you’re clicking on the
<li>
, sometimes you’re clicking on an element within the<li>
. This will change whate.target
is and therefore what.parent()
refers to. (In the stack snippet, the difference is observed by clicking on the text vs. clicking on the bullet point.)Instead of using
.parent()
, use.closest('li')
. That way the logic is always looking at the<li>
for the index: