DreamTeK
DreamTeK

Reputation: 34287

How to target next element with class name?

DEMO


I am doing a simple jquery accordian effect as below.

JQUERY

$(function ($) {
  $('.Accordian').find('.Btn').click(function () {
    $(this).next('.Content').slideToggle('fast');
    $('.Content').not($(this).next()).slideUp('fast');
  });
});

HTML

<div class="Accordian">
  <div class="Btn"></div>
  <div class="Content"></div>
</div>

This work great however if content is placed between .Btn and .Content then it breaks.


QUESTION

  1. How to directly target the next available class name relative to the button clicked?
  2. How to target all elements of a class name except the next available class name relative to button clicked?

Upvotes: 1

Views: 462

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388406

Try with siblings()

$(function ($) {
    $('.Accordian').find('.Btn').click(function () {
        //cache the value so that it can be used in the next statement
        var $content = $(this).siblings('.Content').slideToggle('fast');
        $('.Content').not($content).slideUp('fast');
    });
});

Upvotes: 5

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

Try to use .nextAll() along with .first() to accomplish your task, Actually here we have used .first() for a safety purpose.

  $('.Accordian').find('.Btn').click(function () {
    var targetElem = $(this).nextAll('.Content').first();
    targetElem.slideToggle('fast');
    $('.Content').not(targetElem).slideUp('fast');
  });

DEMO

Upvotes: 1

Related Questions