0

I've got some jQuery that expands a div header when clicked to reveal a subheader. Another click on this subheader then reveals content. However there are two subheaders and I can only get the first to reveal.

I tried changing the selectors to the format recommended on stackoverflow.com/questions/1041344 but this only resulted in the subheaders not even being hidden when the page loads. This is what I've got so far:

jQuery:

<script type="text/javascript">
jQuery(document).ready(function() {
    jQuery(".subheadingFrame, .subheadingEngine").hide();
    jQuery(".heading").click(function()
    {
        jQuery(this).next(".subheadingFrame, .subheadingEngine").slideToggle(500);
    });
    jQuery(".content").hide();
    jQuery(".subheadingFrame, .subheadingEngine").click(function()
    {
        jQuery(this).next(".content").slideToggle(500);
    });
});
</script>

HTML:

<div id="divSparesSubHeader" class="heading">Benelli1</div>
<div id="divSparesLastHeader" class="subheadingFrame">Frame/Subheader1</div>
<div id="divSparesItem" class="content">Content 1</div>
<div id="divSparesLastHeader" class="subheadingEngine">Engine/Subheader2</div>
<div id="divSparesItem" class="content">Content 2</div>

I've got the page up here if anyone could assist?

Community
  • 1
  • 1
Hansel
  • 35
  • 5

1 Answers1

2

Try this

jQuery(".heading").click(function(){
        jQuery(this).nextAll(".subheadingFrame").first().slideToggle(500);
        jQuery(this).nextAll(".subheadingEngine").first().slideToggle(500);
});

.next() only targets the immediate sibling of .heading .. So if it is not found it will return an empty list..

So in such cases better to target the elements using .nextAll() and .first()

Check Fiddle

Sushanth --
  • 55,259
  • 9
  • 66
  • 105
  • Thanks Sushanth, I see the fiddle works exactly as I'd like it to but I've double-checked my code and the heading now doesn't expand anymore (see link to page in question). Is there any chance the div id's are conflicting? I saw somewhere that one could define the classes by jQuery(this).nextAll("#divID.subheadingFrame")...? – Hansel Oct 30 '12 at 20:38
  • Are the id's unique on the page.. Or do you have duplicated id's – Sushanth -- Oct 30 '12 at 20:40
  • The problem is that your page has duplicated id's on the page.. So when you try accessing it by id .. It will only get the first as the ID is supposed to be unique on your page... Think jQuery(this).nextAll(".subheadingFrame").first() should work – Sushanth -- Oct 30 '12 at 20:42
  • My first html was referencing ...jquery/1.3.2/jquery.min.js but I changed it to .../1.8.2/... as used by fiddle ... and it worked! Thanks Sushanth you saved me a lot of frustration! – Hansel Oct 30 '12 at 21:01
  • @Hansel .. Glad to have helped :) – Sushanth -- Oct 30 '12 at 21:02