I try to find a next or prev element of current element. But next() and prev() function can only work in a scope, it can not reach outside. For an example this is what I want to achieve:
<ul id="ul1">
<li>1</li>
<li>2</li>
<li>3</li>
<li>
<ul id="ul2">
<li>4</li>
<li>
<ul id="ul3">
<li>5</li>
<li>6</li>
</ul>
</li>
<li>7</li>
<li>8</li>
</ul>
</li>
<li>9</li>
</ul>
If current element is ul1, next element is <li>1</li>, prev element is null.
If current element is <li>1</li>, next element is <li>2</li>, prev element is ul1
If current element is <li>8</li>, next element is <li>9</li>, prev element is <li>7</li>
First of all, this was a really neat problem. Thanks for posting!
I accomplished this with a chained jQuery statement. Only thing is, if you run
previous()on the topulyou’ll getbody. Which I think technically makes sense. However, if this isn’t the desired behavior, see my update below.Usage:
next("#ul3")returns<li>5</li>Next:
Previous:
Update If you want to limit the upper most node previous can be, you could do:
http://jsfiddle.net/andrewwhitaker/n89dz/
Another Update: Here’s a jQuery plugin for convenience:
Expanded example here: http://jsfiddle.net/andrewwhitaker/KzyAY/