UNPKG

@uswds/uswds

Version:

Open source UI components and visual style guide for U.S. government websites

30 lines (26 loc) 923 B
/** * @name isElement * @desc returns whether or not the given argument is a DOM element. * @param {any} value * @return {boolean} */ const isElement = (value) => value && typeof value === "object" && value.nodeType === 1; /** * @name select * @desc selects elements from the DOM by class selector or ID selector. * @param {string} selector - The selector to traverse the DOM with. * @param {Document|HTMLElement?} context - The context to traverse the DOM * in. If not provided, it defaults to the document. * @return {HTMLElement[]} - An array of DOM nodes or an empty array. */ module.exports = (selector, context) => { if (typeof selector !== "string") { return []; } if (!context || !isElement(context)) { context = window.document; // eslint-disable-line no-param-reassign } const selection = context.querySelectorAll(selector); return Array.prototype.slice.call(selection); };