Selector.prevSibling Method

Returns an array of elements that share the parent with the method target, and precede the target in their parent’s childNodes collection.



Selector().prevSibling() → Selector

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


Selector().prevSibling(index) → Selector

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

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


Selector().prevSibling(cssSelector) → Selector

Looks for preceding element siblings that match the CSS Selector.

Argument Type Description
cssSelector String CSS Selector

prevSibling(filterFn, dependencies)

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

Filters preceding element siblings with a function.

Argument Type Description
filterFn Function The filter function.
dependencies (optional) Object Functions, variables, or objects passed to the filterFn function.

See Filter DOM With A Function.


// Selects all preceding siblings of all p elements.
const siblingsP = Selector('p').prevSibling();

// Selects all closest preceding siblings of all button elements.
const closestSiblingsButton = Selector('button').prevSibling(0);

// Selects all furthest preceding siblings of all option elements.
const furthestSiblingsOption = Selector('option').prevSibling(-1);

// Selects all p elements that are preceding siblings of a div element.
const pSiblingsDiv = Selector('div').prevSibling('p');

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 });