JQuery next () - Getting the next sibling using only classes

I am trying to create something like a web accordion.

Illustrative example:

[TITLE DIV 1] [CONTENT DIV 1] [TITLE DIV 2] [CONTENT DIV 2] [TITLE DIV 3] [CONTENT DIV 3] 

I want to be able to switch (jquery toggle () function) to "Content Div" by clicking on the corresponding "Title Div".

I tried the following, but it does not work.

http://jsfiddle.net/Cs3YY/

HTML:

 <div class="topSeparator"></div> <div class="titleDiv"> <h1>Title 1</h1> </div> <div class="bottomSeparator"></div> <div class="contentDiv"><h2>Content 1</h2></div> <div class="topSeparator"></div> <div class="titleDiv"> <h1>Title 2</h1> </div> <div class="bottomSeparator"></div> <div class="contentDiv"><h2>Content 2</h2></div> 

Jquery:

 $('.titleDiv').click(function() { $(this).next('.contentDiv').toggle(); }); 

http://jsfiddle.net/Cs3YY/

I would describe my functional process as such:

  • When you click on an element with a class named "titleDiv", do:

1.1. Select an item with a click.

1.1.1. Select the next sibling of this element with a click with a class named "contentDiv";

1.1.1.1. Make the toggle () function act on this last element (with a class called "contentDiv");

It seems I'm wrong or something is missing.

.

I enable jquery 1.8.3 (correct).

This works when using an identifier instead of classes (I try to avoid using them).

I put a warning inside the click function and it works (problem inside it).

+8
jquery class next siblings
source share
2 answers

Use .nextAll() and :first to get the next contentDiv

  $(this).nextAll('.contentDiv:first').toggle(); 

Demo here http://jsfiddle.net/Cs3YY/1/

+25
source share

Although, this is because next () selects bottomSeparator. You can use this trick

 $('.titleDiv').click(function() { $(this).next().next().toggle(); }); 

http://jsfiddle.net/Cs3YY/12/

-one
source share

All Articles