vanillajs-browser-helpers
Version:
Collection of convenience code snippets (helpers) that aims to make it a little easier to work with vanilla JS in the browser
69 lines (68 loc) • 1.88 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.nextSiblings = exports.previousSiblings = void 0;
const isDOMElement_1 = __importDefault(require("./isDOMElement"));
const isDOMChildNode_1 = __importDefault(require("./isDOMChildNode"));
const getSiblings = (type) => (elm) => {
if (!(0, isDOMElement_1.default)(elm) || !(0, isDOMChildNode_1.default)(elm)) {
return [];
}
const siblings = [];
const next = type === 'next';
const all = type === 'all';
let sibling = next
? elm.nextElementSibling
: elm.parentElement.firstElementChild;
while (sibling) {
if (next || sibling !== elm) {
siblings.push(sibling);
}
else if (!all) {
break;
}
sibling = sibling.nextElementSibling;
}
return siblings;
};
/**
* Get all sibling elements before a given DOM element in the structure
*
* @param elm - DOM element to find siblings of
* @return Collection of sibling elements
*
* @example
*
* ```ts
* previousSiblings(someElement);
* ```
*/
exports.previousSiblings = getSiblings('prev');
/**
* Get all sibling elements after a given DOM element in the structure
*
* @param elm - DOM element to find siblings of
* @return Collection of sibling elements
*
* @example
*
* ```ts
* nextSiblings(someElement);
* ```
*/
exports.nextSiblings = getSiblings('next');
/**
* Get all sibling elements of a given DOM element
*
* @param elm - DOM element to find siblings of
* @return Collection of sibling elements
*
* @example
*
* ```ts
* siblings(someElement);
* ```
*/
exports.default = getSiblings('all');