packages/uswds-core/src/js/utils/select-or-matches.js
const select = require("./select");
/**
* @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 selectOrMatches
* @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) => {
const selection = select(selector, context);
if (typeof selector !== "string") {
return selection;
}
if (isElement(context) && context.matches(selector)) {
selection.push(context);
}
return selection;
};