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 the siblings of all the input elements.
const siblingsInput = Selector('input').sibling();

// Out of all the siblings of all the div elements,
// selects those that are first in their parent's child lists.
const closestSiblingsDiv = Selector('div').sibling(0);

// Out of all the siblings of all the select elements,
// selects those that are last in their parent's child lists.
const furthestSiblingsFieldset = Selector('select').sibling(-1);

// Selects all the fieldset elements that share the parent with a `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 sibling that precedes <section>
    // idx === the sibling's index
    // 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 });