UNPKG

@gravityforms/utils

Version:
45 lines (43 loc) 1.68 kB
import convertElements from './convert-elements'; /** * @module getNodes * @description A utility to get nodes and return an array/nodelist of them. Abstracts the need * to pass `[data-js="some-string"]` as simply `some-string`. Will also convert the nodelist to an * array if that arg is true, and has a parent to search from. A custom selector string can be used * if the 4th argument is true. * * @since 1.0.0 * * @param {string} selector The selector string to search for. If arg 4 is false (default) * then we search for [data-js="selector"]. * @param {boolean} convert Convert the NodeList to an array? Then we can Array.forEach * directly. Uses convertElements from above. * @param {HTMLElement|Document} node Parent node to search from. Defaults to document. * @param {boolean} custom Is this a custom selector where we don't want to use the * data-js attribute? * @requires convertElements * * @return {NodeList|Array} Returns either a NodeList or an Array of HTMLElements. * * @example * import { getNodes } from "@gravityforms/utils"; * * function Example() { * const nodes = getNodes( '.some-custom-selector', true, document.body, true ); * return nodes; * } * */ export default function getNodes( selector = '', convert = false, node = document, custom = false ) { const selectorString = custom ? selector : `[data-js="${ selector }"]`; let nodes = node.querySelectorAll( selectorString ); if ( convert ) { nodes = convertElements( nodes ); } return nodes; }