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

33 lines (32 loc) 1.13 kB
import isString from 'vanillajs-helpers/isString'; import findByClass from './findByClass'; import findById from './findById'; import findByTagName from './findByTagName'; import findByQuery from './findByQuery'; function find(elm, selector) { if (isString(elm)) { [elm, selector] = [document, elm]; } const query = selector; const isComplex = [' ', '>', '+', '*', '~', ':', '[', ','] .some((char) => query.indexOf(char) > -1); if (!isComplex) { const firstChar = query[0]; const rest = query.substring(1); const isId = firstChar === '#'; const isClass = firstChar === '.'; const hasClass = rest.indexOf('.') > -1; const hasId = rest.indexOf('#') > -1; if (isId && !hasClass) { return findById(rest); } if (isClass && !hasId) { return findByClass(elm, rest.replace(/\./g, ' ')); } if (!isClass && !isId && !(hasId || hasClass)) { return findByTagName(elm, selector); } } return findByQuery(elm, query); } export default find;