What is the perfect way to find all nextSiblings and previousSiblings in JavaScript. I tried few ways but not getting accurate solution. If any element is selected, I need t
Just my two cents here, I made a couple of functions to get all the previos and the next siblings of any element.
const getPreviousAll = element => {
const previousAllFound = [];
const getPrevious = element => {
if (element !== null) {
previousAllFound.push(element);
const previousFound = element.previousElementSibling;
if (previousFound !== null) {
getPrevious(previousFound);
}
}
};
getPrevious(element.previousElementSibling);
return previousAllFound;
};
const getNextAll = element => {
const target = element;
const nextAllFound = [];
const getAll = element => {
if (element !== null) {
nextAllFound.push(element);
const nextFound = element.nextElementSibling;
if (nextFound !== null) {
getAll(nextFound);
}
}
};
getAll(element.nextElementSibling);
return nextAllFound;
};
You just have to call this functions with a node that you can get by getElementById.