I’m trying to get the index of a tab when it opens in Twitter Bootstrap (3.3), but it keeps giving me an index of 0
. I’ve checked out this question but a)
it’s apparently for an older version of Bootstrap (shown
instead of shown.bs.tab
, etc), and b)
I tried to use an updated version of the code(shown.bs.tab
) and it didn’t work.
Any idea of how to do this in Bootstrap 3.3?
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
console.log($(e.target).index());
});
4
Answers
You have to use
.parent()
to target the parentli
instead of$(e.target).index()
that get the index ofa
insideli
(that way it’s return always 0) :Hope this helps.
I think you’re trying to get the index of some element relative to a set of elements. Try this instead:
You can find the parent
li
of the the current a by using.closest()
and find itsindex
.Working example : http://jsfiddle.net/eazg9hoe/1/
$(e.target).index()
will get the index of the element in relation of the parent. Since you are firing from the<a>
and the parent is the<li>
the index will always be 0.If you jump up to the parent(
<li>
) and find the index of that since you will be checking the index of the<li>
in relation to the<ul>
you will get the correct index.If you did want to find out the index of the tab in relation to all of the
$('a[data-toggle="tab"]')
items. You could also use$.inArray(object,array)
Examples here:
http://jsfiddle.net/zdd96tc6/