TheAlbear
TheAlbear

Reputation: 5585

jQuery select next closest class

I have a simple list of FAQ's

<div class='qcontainer'>
    <p>Q:</p>
    <div class='question'>Question</div>
</div>
<div class='acontainer'>
    <p>A:</p>
    <div class='answer'><p>Answer</p></div>
</div>
<div class='qcontainer'>
    <p>Q:</p>
    <div class='question'>Question</div>
</div>
<div class='acontainer'>
    <p>A:</p>
    <div class='answer'><p>Answer</p></div>
</div>

All I am trying to do is a toggle the visable state of the next answerr when the question is clicked.

So far I have got

   $('.qcontainer').bind("click", function (e) {
        $('.qcontainer').next('.acontainer').toggle(400);
    });

But this toggles all the items, what i want to do is just target teh answer for the clicked question. so the next item in the list from the clicked object.

Upvotes: 2

Views: 2243

Answers (4)

Try this, tell me if it works. In the answer DIV you have one unclosed "DIV".

    <div class='qcontainer'>
        <p>Q:1</p>
        <div class='question'>Question</div>
    </div>
    <div class='acontainer'>
        <p>A:</p>
        <div class='answer'><p>Answer</p></div>
    </div>
    <div class='qcontainer'>
        <p>Q:2</p>
        <div class='question'>Question</div>
    </div>
    <div class='acontainer'>
        <p>A:</p>
        <div class='answer'><p>Answer</p></div>
    </div>

Upvotes: 0

Nick
Nick

Reputation: 216

It looks like you were close!

$('.qcontainer').bind("click", function () {
    $(this).next('.acontainer').toggle(400);
});

Upvotes: 2

thecodeparadox
thecodeparadox

Reputation: 87073

$('.qcontainer').bind("click", function (e) {
        $('.acontainer:visible').hide(0);
        $(this).nextAll('.acontainer').show(400);
    });

Upvotes: 2

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

Try like below,

$('.qcontainer').bind("click", function (e) {
    $(this).next().toggle(400);
});

For the markup you have, .next of qcontainer is acontainer and so you can simply use .next to toggle acontainer and not worry about a thing :)

Upvotes: 4

Related Questions