jQuery - Finding next Div

Viewed 86217

I am trying to find the next div after an input button and toggle it.

What am I doing wrong?

JS:

$(".showNextExperience").click(function() {
    $(".experience").show();
});

HTML:

<input class="showNextExperience" >
<div class="experience">Experience 1</div>

<input class="showNextExperience">
<div class="experience">Experience 2</div>

<input class="showNextExperience">
<div class="experience">Experience 3</div>

<input class="showNextExperience" >
<div class="experience">Experience 4</div>

Okay, this DOES NOT work ---

$(".showExperience").click(function() {
    $(this).next(".experience").toggle();
});

<table class="data">
    <tr class="tableHead">
        <td></td>
        <td width="50" align="right"><input type="button" class="showExperience" value="show"></td>
    </tr>
</table>
<div class="experience">2</div>

When I move the input button just above the DIV it works just fine.

$(".showExperience").click(function() {
    $(this).next(".experience").toggle();
});

<input type="button" class="showExperience" value="show">
<div class="experience">2</div>

Can you explain that?

5 Answers

Assuming you have elements between triggering input and manipulated div:

<input class="showNextExperience" >
<p>Hello, new line</p>
<div class="experience">Experience 1</div>

<input class="showNextExperience">
<p>Some text</p>
<div>And an info block</div>
<div class="experience">Experience 2</div>

Then you have to use nextAll to search not only for the very next element but through the whole DOM, which is probably simpler coding than using next().find():

$(".showNextExperience").click(function() {
    $(this).nextAll(".experience").toggle();
});
Related