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');
$('.current').prev()
gives you one element before .current:$('.current').next()
gives you one element after .current: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/
As per your needs, you may use
siblings()
,nextUntil
,prevUntil
,nextAll
,prevAll
functions. Thenext()
andprev()
will get you to just one previous or next element respectively.DEMO
You are doing it right just add the following
try this:
http://jsfiddle.net/yxq39/
or: