UNPKG

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.89 kB
"use strict"; 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; var isDOMElement_1 = __importDefault(require("./isDOMElement")); var isDOMChildNode_1 = __importDefault(require("./isDOMChildNode")); var getSiblings = function (type) { return function (elm) { if (!(0, isDOMElement_1.default)(elm) || !(0, isDOMChildNode_1.default)(elm)) { return []; } var siblings = []; var next = type === 'next'; var all = type === 'all'; var 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');