Skip to content

Instantly share code, notes, and snippets.

@fiveNinePlusR
Forked from pseudosavant/jSugar.js
Created May 19, 2022 18:42
Show Gist options
  • Save fiveNinePlusR/59a5374f8157c2b34b9ca779da89efc7 to your computer and use it in GitHub Desktop.
Save fiveNinePlusR/59a5374f8157c2b34b9ca779da89efc7 to your computer and use it in GitHub Desktop.
Utility function that adds in some jQuery-like syntactic sugar
// 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