Question: I have a set of tab (main-tabs) on a website and each tab has another set of tabs (sub-tabs).
I want to use arrow keys on a keyboard to navigate the tabs, instead of a mouse.

These tabs are just HTML list items `<li>`

When I reach the last sub-tab with the arrow key, I want it to go back to the next main tab so it can display its own sub-tabs, and carry on the navigation inside it.

My question is, how can I detect, in jQuery/javascript, when I've reached the last list item (tab) using the arrow keys i.e. the right arrow key?

Many Thanks

Answer: 
You might be able to use either the [:last](http://api.jquery.com/last-selector/) or [:last-child](http://api.jquery.com/last-child-selector/) selectors in jQuery. Depending on how your `<li>` tags are nested, you might also have to use the [children()](http://api.jquery.com/children/) function along with it.

For example, let's say you have the following markup:

```
    <ul id="nav">
        <li>List item</li>
        <li>List item with sub items
            <ul>
                <li>Sub list item</li>
            </ul>
        </li>
    </ul>

```

This would select the last top-level `<li>`

```
$('ul#nav > li:last').css('border', '1px solid red');

```

![alt text](https://i.stack.imgur.com/SNxnc.png)

---

This would select the last `<li>` traversing the DOM downward. In this case it's the `<li>` with text "Sub list item"

```
$('ul#nav li:last').css('border', '1px solid red');

```

![alt text](https://i.stack.imgur.com/O0TGz.png)

---

This would select any `<li>` tags that are the last child of their parent

```
$('ul#nav li:last-child').css('border', '1px solid red');

```

![alt text](https://i.stack.imgur.com/eSyzO.png)
You can use `.length` to find out if a jQuery selector found anything:

```
var nextSubTab = $(currentSubTab).next("li");
if (nextSubTab.length == 0) {
    // oops, end of this tab, switch to next tab
}

```