Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- generateQueryString
- Returns a kebab-case js hook.
- generateQueryString('fooBar')
- '.js-foo-bar'
- */
- const generateQueryString = (string, prefix = 'js') =>
- `.${prefix}-${string.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase()}`
- /*
- qs / qsa
- Returns a query selector using the
- generateQueryString function
- qs('fooBar')
- document.querySelector('.js-foo-bar')
- */
- const qs = (string, prefix = 'js') =>
- document.querySelector(generateQueryString(string, prefix))
- // Same applies, except uses querySelectorAll
- const qsa = (string, prefix = 'js') =>
- document.querySelectorAll(generateQueryString(string, prefix))
- /*
- qsObj / qsaObj
- Returns an object containing
- query selectors based on provided
- array of strings
- qsObj(['foo', 'bar', 'fooBar'])
- {
- foo: document.querySelector('.js-foo'),
- bar: document.querySelector('.js-bar'),
- fooBar: document.querySelector('.js-foo-bar')
- }
- */
- const qsObj = (array, prefix = 'js') => {
- let object = {}
- array.forEach(i => {
- object[i] = document.querySelector(generateQueryString(i, prefix))
- })
- return object
- }
- // Same applies, except uses querySelectorAll
- const qsaObj = (array, prefix = 'js') => {
- let object = {}
- array.forEach(i => {
- object[i] = document.querySelectorAll(generateQueryString(i, prefix))
- })
- return object
- }
- /*
- manipulateQsObj / manipulateQsaObj
- Runs passed function to every element
- supplied in object.
- */
- const manipulateQsObj = (object, cb) => {
- Object.keys(object).map(key => {
- cb(object[key])
- })
- }
- // Same applies, except uses querySelectorAll
- const manipulateQsaObj = (object, cb) => {
- Object.keys(object).map(key => {
- all(object[key], el => cb(el))
- })
- }
- /*
- first
- Returns first node in list
- */
- const first = hook => hook[0]
- /*
- last
- Returns last node in list
- */
- const last = hook => hook[hook.length - 1]
- /*
- all
- Runs passed function to every
- node in list
- */
- const all = (hook, cb) => {
- ;[].forEach.call(hook, el => cb(el))
- }
- export {
- qs,
- qsa,
- qsObj,
- qsaObj,
- manipulateQsObj,
- manipulateQsaObj,
- first,
- last,
- all
- }
Add Comment
Please, Sign In to add comment