Reputation: 865
jquery accordion
I like to get the index of the h3 within the "xaccordion". Just one link in the accordion will have the class "active" (can also be an id, but I made it an class)
How do I get the index. now the element is not fount and the index is returning -1;
HTML:
<div id="xaccordion">
<h3>title</h3>
<div>
<p>
<a href="#">link</a>
<a class="active" href="#">link</a>
</p>
</div>
<h3>title</h3>
<div>
<p>
<a href="#">link</a>
<a href="#">link</a>
</p>
</div>
</div>
JS:
var active_header = $("#xaccordion a.active").closest("h3");
var active_header_index = $("#xaccordion").index(active_header);
console.log("index: " + active_header_index);
Upvotes: 2
Views: 647
Reputation: 1696
try this code .. hope it works ... made some changes i.e close tag etc.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
var active_header = $("a.active").parents("h3").index();
//var active_header_index = $("#xaccordion").index(active_header);
console.log(active_header);
});
</script>
</head>
<body>
<div id="xaccordion">
<h3>
<div>
<p>
<a href="#">link</a>
<a class="active" href="#">link</a>
</p>
</div>
</h3>
<div>
<p>
<a href="#">link</a>
<a href="#">link</a>
</p>
</div>
</div>
</body>
</html>
Upvotes: 1
Reputation: 2372
I changed your HTML a bit, just so everything is closed:
<div id="xaccordion">
<h3> test </h3>
<div>
<p>
<a href="#">link</a>
<a href="#">link</a>
</p>
</div>
<h3> test2 </h3>
<div>
<p>
<a href="#">link</a>
<a href="#">link</a>
</p>
</div>
<h3> test3 </h3>
<div>
<p>
<a href="#">link</a>
<a class="active" href="#">link</a>
</p>
</div>
</div>
You don't actually need .closest()
in this case. The way you constructed the HTML you can go up two .parent()
This will bring you to the div containing the links. From there you need to look for #xaccordion div
. This will find the index of that div
. From there you could find the sibling H3, but it's not needed since those indexes will be the same.
Here's the JS:
var active_header = $("#xaccordion a.active").parent().parent();
var active_header_index = $("#xaccordion div").index(active_header);
console.log(active_header);
console.log("index: " + active_header_index);
Try moving the class="active"
. This should give the result you're after.
edit: here's a fiddle https://jsfiddle.net/rc8ack29/
Upvotes: 1