Source: https://bigfrontend.dev/problem/Next-Right-Sibiling

// Can do recursively find nextRightSibling of parent and get its first child to get the target node's next right sibling
function nextRightSibling(root, target) {
// If target is null, there is no next right sibling
if (!target) {
return null;
}
// Check target's immediate nextElementSibling to see if there is a next sibling on the same level
if (target.nextElementSibling) {
return target.nextElementSibling;
}
let parent = target.parentElement;
while (parent) {
parent = nextRightSibling(root, parent);
if (parent && parent.firstElementChild) {
return parent.firstElementChild;
}
}
return null;
}