Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Finding next Div

Tags:

jquery

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?

like image 755
Evik James Avatar asked Jul 19 '11 18:07

Evik James


People also ask

How can I get next sibling in jQuery?

jQuery next() Method The next() method returns the next sibling element of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse forward along the next sibling of DOM elements.

What is slice () method in jQuery?

slice() method constructs a new jQuery object containing a subset of the elements specified by the start and, optionally, end argument. The supplied start index identifies the position of one of the elements in the set; if end is omitted, all elements after this one will be included in the result.

How do you get next element in the same class?

To find the next element with specific class:Use the nextElementSibling to get the next element sibling. In a while loop iterate over the next siblings. Check if each element's class list contains the specific class.

What is addBack in jQuery?

addBack() Adds the previous set of elements to the current set. andSelf()


2 Answers

Simply:

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

See:

  • http://api.jquery.com/toggle/
  • http://api.jquery.com/next/
like image 90
karim79 Avatar answered Sep 21 '22 06:09

karim79


$(".showNextExperience").click(function() {
    $(this).next().show();
});
like image 34
zachzurn Avatar answered Sep 18 '22 06:09

zachzurn