Recently I needed to find out the element index of a List element when clicked.

I managed to come up with the code that enabled me to do that using jQuery.

First, you need to set up your HTML code with an id of ‘bourne’. You don’t have to use bourne, use whatever you like.

Loading...

You can see above that I have created an unordered list with an id of ‘bourne’, with 5 list elements inside it.

Now we need to move over to the javascript. I will assume that you have managed to set up a script element in your page header or link to an external JavaScript file.

Whatever you use, insert the following code to trigger the onDomReady, so that this is run once the page is ready.

Loading...

Now that we have set up our entry point, we need to trigger for the on-click event. We want this to be triggered every time a list element is triggered.

We set up the click event, telling it that we want it to attach it to the list elements ID bourne.

Loading...

Now that we have built the click event, you can reference the element by using ‘this’.

Loading...

The above would display an alert box displaying the text of the clicked element.

But what if we want to find out the index of this element so that we can work out its position if it was part of a menu or tab option?

To do this, we need to get every list element and place it in a variable.

Loading...

The new code now puts the clicked elements parent into a variable. The second line displays an alert detailing which element of the array was clicked. It does this by finding the clicked elements index of the parent.

I know this is a script I will be using again soon, so hopefully somebody else might find this useful as well.