In JavaScript, you can use the nextElementSibling and previousElementSibling properties to get the next and previous siblings of an element.

Let us say you've got the following list of items:

<ul>
    <li>🍔</li>
    <li>🍕</li>
    <li id="drink">🍹</li>
    <li>🍲</li>
    <li>🍩</li>
</ul>

Now you want to get the list item immediately before and after #drink.

You can use the previousElementSibling property to get the sibling before an element. To get the sibling immediately after an element, use the nextElementSibling property:

const drink = document.querySelector('#drink');

// get previous sibling
const pizza = drink.previousElementSibling;

console.log(pizza.innerText); // 🍕

// get next sibling
var pot = drink.nextElementSibling;

console.log(pot.innerText); // 🍲

Get all previous siblings

To get all the previous siblings of an element, you can use the following code snippet:

const previousSiblings = (elem) => {
    // create an empty array
    let siblings = [];

    // loop through previous siblings until `null`
    while (elem = elem.previousElementSibling) {
        // push sibling to array
        siblings.push(elem);
    }
    return siblings;
};

const drink = document.querySelector('#drink');

// get all previous siblings
const siblings = previousSiblings(drink);

siblings.forEach(li => console.log(li.innerText));

// 🍕
// 🍔

Get all next siblings

The following example demonstrates how you get all the next siblings of an element:

const nextSiblings = (elem) => {
    // create an empty array
    let siblings = [];

    // loop through next siblings until `null`
    while (elem = elem.nextElementSibling) {
        // push sibling to array
        siblings.push(elem);
    }
    return siblings;
};

const drink = document.querySelector('#drink');

// get all the next siblings
const siblings = nextSiblings(drink);

siblings.forEach(li => console.log(li.innerText));

// 🍲
// 🍩

What about nextSibling and previusSibling?

You may have seen or heard of the nextSibling and previousSibling properties on StackOverflow.

Both these properties more or less do the same thing, return the next and previous siblings of an element. However, there is a fundamental difference between them.

The nextSibling and previousSibling properties return the next and previous sibling nodes that might be text nodes (whitespace) or comment nodes. However, nextElementSibling and previousElementSibling always return element sibling nodes that excludes whitespace and comments.

Browser compatibility

The nextElementSibling and previousElementSibling properties work in all modern browsers and IE9 and above.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.