1

How can I get the index of the clicked element in a list?

So if I have the following list:

  • First
  • Second
  • Third

When I click Third, I would like to get the index 2, provided the index starts with 0.

With my code I only get 0s:

HTML:

<ul>
  <li><a href="#" class="listElem">First</a></li>
  <li><a href="#" class="listElem">Second</a></li>
  <li><a href="#" class="listElem">Third</a></li>
</ul>

JS:

$(".listElem").click(function(param) {
  console.log($(this).index());
});

Here is a fiddle.

1

3 Answers 3

3

You should use parent() to return index of li DEMO

$(".listElem").click(function(param) {
  console.log($(this).parent().index());
});
Sign up to request clarification or add additional context in comments.

Comments

0

Use this:

$(".listElem").click(function(param) {
  console.log($(".listElem").index(this));
});

DEMO

Comments

0

Try this

$("li").click(function() {
  var index = $(this).parent().children().index(this);
  alert("You clicked item " + index);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.