views:

29

answers:

1

I'm pretty new to jQuery... so far I'm impressed. But I encountered a situation today that is giving me trouble. I want to use .html() to get some raw text and use that in a selector, but that function only returns the first element.

In the following structure, how can I get ALL of the "toggle_containerLG" divs to show when I click on the trigger "Some Header"?

<h6 class="trigger active">Some Header</h6>
<ul>
    <li><a href="#" class="trigger">Title One</a></li>
    <li><a href="#" class="trigger">Title Two</a></li>
    <li><a href="#" class="trigger">Title Three</a></li>
</ul>   

<div class="toggle_containerLG" id='Title_One'></div>  <!-- show these! -->
<div class="toggle_containerLG" id='Title_Two'></div>
<div class="toggle_containerLG" id='Title_Three'></div>
<div class="toggle_containerLG" id='Title_Four'></div> <!-- not this one! -->

I can't use $(".toggle_containerLG") because there are others I don't want to expand... I just want the ones listed under "Some Header". Seems like there should be an easy way to do it... and I'm just missing it because I don't know jQuery very well.

A: 

You can loop though the <ul> that follows the header if you want using .each(), like this:

​$("h6.trigger").click(function() {
    $(this).next("ul").find("a").each(function() {
        $("#" + $(this).text().replace(" ","_")).slideToggle();
    });
});​​​​​​​​​​

You can see a demo here

A better approach might be to use the href attribute for the ID, like this:

<a href="#Title_One" class="trigger">Title One</a>

Then you can use jQuery like this:

$(".trigger").click(function() {
    $(this).next("ul").find("a").each(function() {
        $(this.hash).slideToggle();
    });
});​

You can see a demo like that here

Nick Craver
Thanks Nick! It looks like each() is the key I was missing. Demo is awesome. The # version looks a little cleaner, but has the unfortunate side effect of actually shifting the page up/down.
Bryan
@Bryan - You can prevent the jumping by doing `$("a.trigger").click(function() { return false; });` or `$("a.trigger").live('click', function() { return false; });` or use `function(e) { e.preventDefault(); }` with `.live()` or `.click()`, whichever combination you want :) This prevents the normal browser scrolling behavior.
Nick Craver