I am using twitter bootstrap’s tab layout. For each tab i have attached click event handler. Inside the click handler i wanted to find out the index of the tab that is clicked. Below is by code
<ul class="nav nav-tabs">
<li class="active"><a data-toggle="tab" href="#tab1">Tab 1</a></li>
<li><a data-toggle="tab" href="#tab2">Tab 2</a></li>
<li><a data-toggle="tab" href="#tab3">Tab 3</a></li>
</ul>
<div class="tab-content">
<div id="tab1" class="tab-pane fade in active">
</div>
<div id="tab2" class="tab-pane fade">
</div>
<div id="tab3" class="tab-pane fade">
</div>
</div>
Javascript
$(".nav.nav-tabs > li > a").on('click', function (e) {
var index = $(".nav.nav-tabs > li > a").index(this);
// do something here
})
The above code works as long as i have single nav-tabs
layout on the same page.
But if i have multiple nav-tabs
on the same page the above code may not return correct index or even if it returns correct index the code is not optimized to look only inside clicked nav-tabs
.
I can scope the jquery select by passing id
or custom class name. However i’m trying to find if there is generic way to find the index of clicked <a>
2
Answers
Get the
.nav-tabs
which contains the clicked element usingclosest()
method and check index within the children element.Or get the index of
li
element within the siblings whereli
can get usingparent()
method.see this exmaple
lets say you have the following HTML:
then you can get clicked tab index like this:
please see working example here