-
-
Save krackers/7a94c7cd1ce42b4168d0457e27a75bb4 to your computer and use it in GitHub Desktop.
Utility function that adds in some jQuery-like syntactic sugar
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // jQuery-like syntactic sugar. Only queries for one element. Does not loop over multiple like jQuery | |
| function $(query) { | |
| if (typeof query === 'undefined') throw 'No query provided to $'; | |
| var el; | |
| if (typeof query.nodeType === 'string') { | |
| el = query; | |
| } else if (typeof query === 'string' && query[0] === '<') { | |
| const container = document.createElement('div'); | |
| container.innerHTML = query; | |
| el = container.firstChild; | |
| } else if (typeof query === 'string') { | |
| el = document.querySelector(query); | |
| } else { | |
| el = query; | |
| } | |
| if (el) { | |
| el.on = (e, fn, ...args) => { | |
| if (args.length > 0) { | |
| el.addEventListener(e, fn, ...args); | |
| } else { | |
| el.addEventListener(e, fn, false); | |
| } | |
| return el; | |
| }; | |
| el.off = (eventType, callback) => { el.removeEventListener(eventType, callback); return el; } | |
| el.once = (e, fn) => el.addEventListener(e, fn, {once: true}); | |
| el.trigger = (eventOrType, optDetail) => { | |
| const detail = (optDetail ? { detail: optDetail } : undefined); | |
| const e = (typeof eventOrType === 'string' ? new CustomEvent(eventOrType, detail) : eventOrType); | |
| el.dispatchEvent(e); | |
| return el; | |
| }; | |
| el.hasClass = c => el.classList.contains(c); | |
| el.addClass = c => { el.classList.add(c); return el; } | |
| el.removeClass = c => { el.classList.remove(c); return el; } | |
| el.toggleClass = c => { el.classList.toggle(c); return el; } | |
| el.append = element => { el.appendChild($(element)); return el; } | |
| el.remove = () => { | |
| if (el && el.parentNode) el.parentNode.removeChild(el); | |
| return el; | |
| } | |
| el.show = () => { el.style.display = 'initial'; return el; } | |
| el.attr = (name, val) => { | |
| if (isUndefined(val)) { | |
| return el.getAttribute(name); | |
| } else { | |
| el.setAttribute(name, val); | |
| return el; | |
| } | |
| }; | |
| el.removeAttr = name => { el.removeAttribute(name); return el; } | |
| el.val = () => el.value; | |
| el.find = q => $(q, el); | |
| el.parent = () => $(el.parentElement); | |
| el.html = h => { | |
| if (isUndefined(h)) { | |
| return el.innerHTML; | |
| } else { | |
| el.innerHTML = h; | |
| return el; | |
| } | |
| }; | |
| } | |
| function isUndefined(v) { | |
| return typeof v === 'undefined'; | |
| } | |
| return el; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment