Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm trying to create something like a web accordion.

Visual 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 toggle (jquery function toggle()) a "Content Div" by clicking on the respective "Title Div".

I've tried the following, but it doesn't 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 function process as such:

  1. When you click on a element with a class named "titleDiv", do:

1.1. Select that clicked element;

1.1.1. Select the next sibling of that clicked element with a class named "contentDiv";

1.1.1.1. Make the function toggle() act on this last element (With the class named "contentDiv");

It seems that I'm wrong or I'm missing something.

.

I'm including jquery 1.8.3 (Correctly).

This works when using ID's instead of classes (I'm trying to avoid using them).

I placed an alert inside the click function and it works (The problem is inside it).

like image 786
Edu Avatar asked Feb 15 '13 13:02

Edu


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 does siblings do in jQuery?

The siblings() is an inbuilt method in jQuery which is used to find all siblings elements of the selected element. The siblings are those having same parent element in DOM Tree.

Which of the following methods returns a reference to the next child of the current element's parent?

nextSibling returns the next sibling node: An element node, a text node, or a comment node.

Is jQuery a selector?

The is( selector ) method checks the current selection against an expression and returns true, if at least one element of the selection fits the given selector. If no element fits, or the selector is not valid, then the response will be 'false'.


1 Answers

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

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

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

like image 93
Anton Avatar answered Sep 27 '22 22:09

Anton