Selector.parent Method

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

Syntax

parent

Selector().parent() → Selector

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

parent(index)

Selector().parent(index) → Selector

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

Argument Type Description
index Number Zero-based index (0 is the closest parent).

parent(cssSelector)

Selector().parent(cssSelector) → Selector

Looks for parent elements that match the CSS Selector parameter.

Argument Type Description
cssSelector String CSS Selector.

parent(filterFn, dependencies)

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

Filters parent elements with a function.

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

See Filter DOM With A Function.

Examples

// Returns all the ancestors of all the div elements.
const divParents = Selector('div').parent();

// Returns all the closest parents of all the input elements.
const inputClosestParents = Selector('input').parent(0);

// Returns the most distant ancestors of all the labels.
const columnFurthestParents = Selector('label').parent(-1);

// Returns all the divs that have fieldset children.
const fieldsetDivParents = Selector('fieldset').parent('div');

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