Selector.nextSibling Method
Returns an array of elements that share the parent with the method target(s), and follow the target(s) in the parent’s childNodes
collection.
Syntax
nextSibling
Selector().nextSibling() → Selector
Returns an array of succeeding sibling elements, starting with the closest relatives.
nextSibling(index)
Selector().nextSibling(index) → Selector
Returns an array of n-th closest succeeding sibling elements. The n parameter is an integer. If n is negative, the method returns an array of n-th most distant succeeding sibling elements.
Argument | Type | Description |
---|---|---|
index |
Number | The index of the sibling as it appears in the parent’s childNodes collection. |
nextSibling(cssSelector)
Selector().nextSibling(cssSelector) → Selector
Looks for succeeding element siblings that match the CSS Selector.
Argument | Type | Description |
---|---|---|
cssSelector |
String | CSS Selector |
nextSibling(filterFn, dependencies)
Selector().nextSibling(filterFn, dependencies) → Selector
Filters succeeding 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.
Examples
// Selects all the succeeding siblings of all the 'header' elements.
const siblingsHeader = Selector('header').nextSibling();
// Selects all the closest succeeding siblings of all the div elements.
const closestSiblingsDiv = Selector('div').nextSibling(0);
// Selects all the most distant succeeding siblings of all the fieldset elements.
const furthestSiblingsFieldset = Selector('fieldset').nextSibling(-1);
// Selects all the p elements that follow legend elements.
const pSiblingsDiv = Selector('legend').nextSibling('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 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 });