3

I have five anchor elements in my navigation. I want to get index of clicked element with jQuery. I tried this code.

$('.navigation ul li a').click(function(e) { e.preventDefault(); var el = $(this).index(); console.log(el); }) 

But every time I get zero in console.

https://jsfiddle.net/2hg2fkda/ fiddle is here.

Any help will be appreciated. Thanks,

4 Answers 4

5

try this:

$('.navigation ul li').click(function(e) { e.preventDefault(); var el = $(this).index(); console.log(el); }) 
Sign up to request clarification or add additional context in comments.

Comments

4

Index can be fetched if its list . Replace your code here -

var el = $(this).parent().index(); 

LIVE https://jsfiddle.net/mailmerohit5/hg0dqnxb/

Comments

1

you can try this one:

$('.navigation ul li ').click(function (e) { alert($(this).index()); }); 

DEMO

Comments

1

you can also try this!!

var el = $(this).closest('li').index(); 

Demo

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.