Vincent
Vincent

Reputation: 325

Toggle one div with same class

How to use Toggle when several div have the same class with jQuery? I want to show just one div on click.

JavaScript

$(".help_content").hide();
$(".help_target").click(function()
{
    $('.help_content').toggle(); // I also tried with $(".help_content").show();
});

HTML

<div id="foo">
    <p class="help_target">
            <a href="#">Click</a>
    </p>
</div>
<p class="help_content">Asia</p>

<div id="some">
    <p class="help_target">
        <a href="#">Click</a>
    </p>
</div>
<p class="help_content">Africa</p>

I can't use next() since .help_content is not a descendant of .help_target. (I want to use .help_target in fieldsets and display .help_content out of fieldsets).

Upvotes: 1

Views: 5023

Answers (6)

zindel
zindel

Reputation: 1875

$('.help_target>a').click(function() {
   $('.help_content').hide();
   $(this).closest('.help_target').parent().next('.help_content').eq(0).show();
   return false;
});

Upvotes: 0

Sangeet Menon
Sangeet Menon

Reputation: 9915

Why not give the div a unique Id and then call the toggle function

$("#help_content_DIV_ID").toggle();

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 360016

You can do this:

$(".help_content").hide();
$(".help_target").click(function()
{
    $(this).parent().next('.help_content').toggle();
});

See it in action: http://jsfiddle.net/mattball/X7p28/

Upvotes: 3

Mark Coleman
Mark Coleman

Reputation: 40863

You can achieve this by calling .parent() and then .next()

$(".help_target").click(function()
{
    $(this).parent().next('.help_content').toggle();
});

Code example on jsfiddle.

Upvotes: 0

karim79
karim79

Reputation: 342765

Use:

$(this).closest("div").next(".help_content").toggle();

Upvotes: 3

Headshota
Headshota

Reputation: 21449

$(".help_target").click(function()
{
    $(this).parent().next().toggle(); // I also try with $(".help_content").show();
});

Upvotes: 0

Related Questions