Rice_Crisp
Rice_Crisp

Reputation: 1261

JQuery select following div of each instance of a class

I have several h1's with a div below them. Is there any way to select only the div right after the h1? The code I have right now slideToggles all of the div's with a clickable class.

JQuery

$(".clickable").click(function() {
    $(".clickable + div").slideToggle(1000);
});

HTML

<h1 class="clickable">HTML/CSS</h1>
<div class="hidden">
    <p>Here are my examples</p>
    <p>Here are my examples</p>
</div>

Upvotes: 0

Views: 111

Answers (3)

j08691
j08691

Reputation: 208032

Use $(this) to refer to the H1 you're clicking on. By using $(".clickable + div") within the click handler you refer to all divs that are children of any H1. By using $(this) within the event handler you refer just to the one clicked.

$(".clickable").click(function() {
    $(this).next().slideToggle(1000);
});

jsFiddle example

Upvotes: 0

Adil Shaikh
Adil Shaikh

Reputation: 44740

You need this -

$(".clickable").click(function() {
    $(this).next('div.hidden').slideToggle(1000);
});

Upvotes: 1

lonesomeday
lonesomeday

Reputation: 238075

next does all you want:

$(".clickable").click(function() {
    $(this).next().slideToggle(1000);
});

Upvotes: 3

Related Questions