Get next / previous element using JavaScript?
Fire up your element traversal engines with .nextElementSibling
and .previousElementSibling
.
Fetch next / previous elements faster than Flash can run; no need for loops or fancy recursion.
Exception handling
Act like Batman, be ready for everything including your .nextElementSibling
or .previousElementSibling
returning null
if you're already at the end or the start.
jQuery shortcut
If you're a jQuery fan, this Caped Crusader came prepared with that too:
jQuery conveniently handles cross-browser peculiarities, so you can be Bruce Wayne in the boardroom (no tech stress!).
Advanced sibling workflow
Element tag
test before you leap
.nextSibling
and .previousSibling
might catch you off-guard by returning text nodes or comments. Like Alfred, always be prepared:
Dynamic sibling selection
Programmatically rummage through DOM's bat-gadget bag:
Bounds checking is crucial here as Batman is allergic to accessing indices that do not exist.
Brushing up with innerHTML and CSS classes
Adjust gadget features on-the-fly
Upgrade your Bat-gadgets while in action:
Don the Bat-suit
Stylize your siblings (Bat-suit not included):
Super-styling and dynamic feature upgrades: now that's golden-age comic book stuff!
Was this article helpful?