I have a nav with some child a-elements. I added a click function to those elements, and want to know, which one was clicked. As there can be a span inside (but don’t have to) the a-tag as well I used this code to get the index:
HTML
<nav>
<a href=""><span></span>Link text</a>
<a href=""><span></span>Link text</a>
</nav>
JavaScript
var items = $('nav > a');
items.click( function(event) {
var target = ( $(event.target).is('span') ? $(event.target).parent() : $(event.target) );
var key = items.index( target );
console.log( key );
event.preventDefault();
});
So my question is: Is there a better/short/faster way of writing this?
As the click will propagate through the span to the
<a/>you should be able to just use$(this).index():