• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / Miscellaneous / Get Siblings of an Element

Get Siblings of an Element

Get Siblings of an Element

This snippet gets the next sibling and previous sibling of an element, using the element.nextSibling and element.previousSibling properties.

const previous = element.previousSibling;
const next = element.nextSibling;

The following helper function gets all the following sibling of an element:

const getNextSiblings = (e) => {
    let siblings = [];
    while (e = e.nextSibling) {
        siblings.push(e);
    }
    return siblings;
}

And the following helper function gets all the previous siblings of an element:

const getPreviousSiblings = (e) => {
    let siblings = [];
    while (e = e.previousSibling) {
        siblings.push(e);
    }
    return siblings;
}

The following helper function gets all siblings of an element:

const getSiblings = (e) => {
    let siblings = [];

    e = e.parentNode.firstChild;
    do {
        siblings.push(e);
    } while (e = e.nextSibling);

    return siblings;
}

You can add a filter function to the helper function as shown in the following example:

const getSiblings = (e, filter) => {
    let siblings = [];

    e = e.parentNode.firstChild;
    do {
        if (!filter || filter(e)) {
            siblings.push(e);
        }
    } while (e = e.nextSibling);

    return siblings;
}

The following example uses the getSiblings() helper function to get all the siblings of an anchor element, which are also anchor elements:

const e = document.querySelector('a.first');

let links = getSiblings(el, (e) => {
    e.nodeName.toLowerCase() === 'a';
});

Source

https://www.javascripttutorial.net/dom/traversing/get-siblings-of-an-element/

Miscellaneous

Related Snippets:

  • Get unique values in an array
  • Show a custom context menu at clicked position
  • Insert an element at the end of a set of elements inside a shared parent
  • Return every nth element in an array

Primary Sidebar

JSON Compare

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2025 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers
Advertisement