import { isObjPrototypeOf } from "./isObjPrototypeOf"; type TCheckedObj = NodeList | HTMLCollection | Node | Element; /** * Получает кликнутые input[type="checkbox"] и input[type="radio"] из элемента * @param obj{NodeList|HTMLCollection|Node|Element} исходный элемент либо коллекция элементов * @param filter{String=} фильтрующий селектор * @returns {HTMLInputElement[]} Возвращает массив отмеченных `checkbox`/`radio`, дополнительно отфильтрованных по `filter` (если он задан). * @example * import { getCheckedBoxes } from "@delement/ui/utils"; * * const checked = getCheckedBoxes(document.querySelector("form") as HTMLFormElement, "[name='roles']"); */ export const getCheckedBoxes = (obj: TCheckedObj, filter: string = ""): HTMLInputElement[] => { const checkedBoxes: HTMLInputElement[] = []; const checkboxes = (isObjPrototypeOf(NodeList.prototype, obj) || isObjPrototypeOf(HTMLCollection.prototype, obj)) ? Array.from(obj as NodeList | HTMLCollection) : Array.from((obj as Element).querySelectorAll("input[type=\"checkbox\"], input[type=\"radio\"]")); checkboxes.forEach((checkbox) => { if (checkbox instanceof HTMLInputElement && checkbox.checked) { if (filter) { try { if (!checkbox.matches(filter)) { return; } } catch (err) { console.error(`[getCheckedBoxes] Invalid filter selector "${filter}"`, err); return; } } checkedBoxes.push(checkbox); } }); return checkedBoxes; };