To get the next sibling and previous sibling of an element, you use the element.nextSibling
and element. previousSibling
properties:
const previous = element.previousSibling;
const next = element.nextSibling;
Code language: JavaScript (javascript)
The following helper function gets all the following sibling of an element:
const getNextSiblings = (e) => {
let siblings = [];
while (e = e.nextSibling) {
siblings.push(e);
}
return siblings;
}
Code language: JavaScript (javascript)
And the following helper function gets all the previous siblings of an element:
const getPreviousSiblings = (e) => {
let siblings = [];
while (e = e.previousSibling) {
siblings.push(e);
}
return siblings;
}
Code language: JavaScript (javascript)
The following helper function gets all siblings of an element:
const getSiblings = (e) => {
let siblings = [];
e = e.parentNode.firstChild;
do {
siblings.push(e);
} while (e = e.nextSibling);
return siblings;
}
Code language: JavaScript (javascript)
Sometimes, you want to filter the siblings of an element e.g., get all siblings of the current element which are the p elements.
To do this, you can add a filter function to the helper function as shown in the following example:
const getSiblings = (e, filter) => {
let siblings = [];
e = e.parentNode.firstChild;
do {
if (!filter || filter(e)) {
siblings.push(e);
}
} while (e = e.nextSibling);
return siblings;
}
Code language: JavaScript (javascript)
The following example uses the getSiblings()
helper function to get all the siblings of an anchor element, which are also anchor elements:
const e = document.querySelector('a.first');
let links = getSiblings(el, (e) => {
e.nodeName.toLowerCase() === 'a';
});
Code language: JavaScript (javascript)
Was this tutorial helpful ?