Selector.sibling Method

Returns an array of elements that share the parent with the method target(s).

Syntax

sibling

Selector().sibling() → Selector

Returns an array of sibling elements, starting with the closest relatives.

sibling(index)

Selector().sibling(index) → Selector

Returns an array of n-th closest sibling nodes. The n parameter is an integer. If n is negative, the method returns an array of n-th most distant sibling nodes.

Argument Type Description
index Number The index of the sibling as it appears in the parent’s childNodes collection.

sibling(cssSelector)

Selector().sibling(cssSelector) → Selector

Looks for element siblings that match the CSS Selector.

Argument Type Description
cssSelector String CSS Selector

sibling(filterFn, dependencies)

Selector().sibling(filterFn [, dependencies]) → Selector

Filters element siblings with a function.

Argument Type Description
filterFn Function Filter function.
dependencies (optional) Object Functions, variables, and objects passed to the filterFn function.

See Filter DOM With A Function.

Examples

// Selects all siblings of all input elements.
const siblingsInput = Selector('input').sibling();

// Selects all div elements' siblings
// that go first in their parent's child lists.
const closestSiblingsDiv = Selector('div').sibling(0);

// Selects all select elements' siblings
// that go last in their parent's child lists.
const furthestSiblingsFieldset = Selector('select').sibling(-1);

// Selects all fieldset elements that are succeeding siblings of an button element.
const pSiblingsDiv = Selector('button').sibling('fieldset');

Filter DOM with a function

To filter the DOM with a client-side filter function, pass a function argument to the method.

The filterFn argument accepts the following parameters:

Parameter Description
node The current node.
idx The index of the current node.
originNode The DOM Node .
Selector('section').prevSibling((node, idx, originNode) => {
    // node === the <section>'s preceding sibling node
    // idx === index of the current <section>'s preceding sibling node
    // originNode === the <section> element
});

Use the dependencies option to pass variables to the filter function.

const isNodeOk = (node, idx, originNode) => {
    console.log({ node, idx, originNode });
    return idx === 6;
};

const filteredDiv = Selector('div').prevSibling((node) => {
    return !isNaN(node.textContent);
}, { isNodeOk });