Reputation: 950
// html
<div id="accordion" >
<h3 class='headAcc' id="head_1">First header</h3>
<div>First content panel</div>
<h3 class='headAcc'id="head_2">Second header</h3>
<div>Second content panel</div>
</div>
//javascript
$('#accordion').accordion({collapsible:true,active:false});
Question: all the tabs are closed on default. So I need to get the index of a tab using header element id. How can I do that.
I have tried following. But no luck. Thanks in advance.
var indexOfheaderOne= $('h3#head_1').index(); //returns 0 which is ok
var indexOfheaderTwo= $('h3#head_2').index(); // returns 2 instead of 1.
//I think the reason is it will count the indexes based on all sibling elements
//not just from header elements. Is there any workaround for this.
Little modification for @Thusar Solution
Suppose that your html contains more <h3>
elements outside accordion. Then following work around will work for that type of scenario.
HTML
<h3 id="test1">Example Head 1</h3>
<h3 id="test2">Example Head 2</h3>
<h3 id="test3">Example Head 3</h3>
<div id="accordion" >
<h3 class='headAcc' id="head_1">First header</h3>
<div>First content panel</div>
<h3 class='headAcc'id="head_2">Second header</h3>
<div>Second content panel</div>
</div>
JavaScript
alert($('h3#head_1').index('h3.headAcc'));//return 0 as expected
alert($('h3#head_2').index());//return 2 because element is in after first tab div
alert($('h3#head_2').index('h3.headAcc'));//return 1 as expected
Upvotes: 0
Views: 4243
Reputation: 1575
$("#accordion").accordion("option", "active", i);
have you try this one ? with accordion it might be in-built function.
Try Demo this.
Upvotes: 0
Reputation: 82913
Your assumption on why it is returning 2 is right.
Change your index selector to as follows:
var indexOfheaderOne= $('h3').index($('#head_1')); //returns 0 which is ok
var indexOfheaderTwo= $('h3').index($('#head_2')); // returns 1.
JsFiddle: http://jsfiddle.net/GxQ3c/2/
Upvotes: 1
Reputation: 57095
var indexOfheaderTwo= $('h3#head_2').index('h3'); //returns 1 as index of h3 with respect to parent is traced and it is the 2nd child of parent with tag h3.
Index starts from 0.
Explanation of the problem.
var indexOfheaderOne= $('h3#head_1').index(); //returns 0 As it is first child of parent div
var indexOfheaderTwo= $('h3#head_2').index(); // returns 2 As it is third child of parent div
Read .index()
Upvotes: 2