we have a series of divs, and we would like to assign different classes to the next and previous siblings of the currently selected DIV.
This is our code:
<div class="panel">DIV content 1</div>
<div class="panel current">DIV content 2</div> //THIS IS THE CURRENTLY SELECTED PANEL
<div class="panel">DIV content 3</div>
<div class="panel">DIV content 4</div>
<div class="panel">DIV content 5</div>
As I understood, the following JQuery code would look for siblings of .current and add the classes next and previous. But since it's looking for .current elements, it'll not find em.
How can I refer to the .current panel and addClass to the next and previous .panel elements?
Thank you.
$('.current').prev().addClass('previous');
$('.current').next().addClass('next');
As per your needs, you may use siblings()
, nextUntil
, prevUntil
, nextAll
, prevAll
functions. The next()
and prev()
will get you to just one previous or next element respectively.
//To select all previous elements of `.current` element:
$('.current').prevAll('.panel').addClass('previous');
//To select all next elements of `.current` element:
$('.current').nextAll('.panel').addClass('next');
DEMO
try this:
$('.current').prevUntil('.panel:first').addClass('previous');
$('.current').nextUntil('.panel:last').addClass('next');
http://jsfiddle.net/yxq39/
or:
$('.current').prevAll().addClass('previous');
$('.current').nextAll().addClass('next');
You are doing it right
just add the following
$('.current').prev(".panel").addClass('previous');
$('.current').next(".panel").addClass('next');
$('.current').prev()
gives you one element before .current:
<div class="panel">DIV content 1</div>
$('.current').next()
gives you one element after .current:
<div class="panel">DIV content 3</div>
See Demo: http://jsfiddle.net/ssNUN/
If you want to get all prev or next elements use nextUntil() and prevUntil().
See Demo: http://jsfiddle.net/YfV5x/