Explain Codes LogoExplain Codes Logo

Get next / previous element using JavaScript?

javascript
dom-manipulation
javascript-advanced
browser-quirks
Nikita BarsukovbyNikita Barsukov·Jan 12, 2025
TLDR

Fire up your element traversal engines with .nextElementSibling and .previousElementSibling.

let batmobile = document.getElementById('batman').nextElementSibling; // Now Robin isn't so boy wonder without Batman, is he? let batwing = document.getElementById('batman').previousElementSibling; // Alfred, brushing up the batwing.

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.

if (!batmobile) console.log('Robin... where\'s Alfred?'); if (!batwing) console.log('Alfred... where\'s the batcave?');

jQuery shortcut

If you're a jQuery fan, this Caped Crusader came prepared with that too:

let $commisionerGordon = $('#batman').next(); let $batcave = $('#batman').prev();

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:

var gadget = document.querySelector('.batGadget'); while(gadget.nextElementSibling && gadget.nextElementSibling.tagName !== 'DIV') { gadget = gadget.nextElementSibling; // Keep gadgeting along }

Dynamic sibling selection

Programmatically rummage through DOM's bat-gadget bag:

var batGadgetsArr = Array.from(document.getElementsByTagName('div')); // Stealthy Batman prefers 'div' disguises var currentGadgetIndex = batGadgetsArr.indexOf(batGadget); var nextBatGadget = batGadgetsArr[currentGadgetIndex + 1]; // Next gadget, Bat-signed and ready var prevBatGadget = batGadgetsArr[currentGadgetIndex - 1]; // Just in case we need that Batcave GPS again

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:

nextBatGadget.innerHTML = 'This bat-gadget has been upgraded!'; // Better, stronger, faster... prevBatGadget.innerHTML = 'This old-school bat-gadget still rocks!'; // Who doesn't love a Bat-throwback?

Don the Bat-suit

Stylize your siblings (Bat-suit not included):

nextBatGadget.classList.add('bat-upgrade'); prevBatGadget.classList.remove('bat-retro');

Super-styling and dynamic feature upgrades: now that's golden-age comic book stuff!