Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save pawel-dubiel/b3b8c561ae3ee0e954f49ec44eea5ff7 to your computer and use it in GitHub Desktop.
Save pawel-dubiel/b3b8c561ae3ee0e954f49ec44eea5ff7 to your computer and use it in GitHub Desktop.
javascript dom manipulation without jquery
function $(id) { return document.getElementById(id); }
function byClass (el, cl) { return el ? el.getElementsByClassName(cl) : [] }
function byTag (el, tg) { return el ? el.getElementsByTagName(tg) : [] }
function allof (cl) { return byClass(document, cl) }
function hasClass (el, cl) { var a = el.className.split(' '); return find(cl, a) }
function addClass (el, cl) { if (el) { var a = el.className.split(' '); if (!find(cl, a)) { a.unshift(cl); el.className = a.join(' ')}} }
function remClass (el, cl) { if (el) { var a = el.className.split(' '); rem(a, cl); el.className = a.join(' ') } }
function html (el) { return el ? el.innerHTML : null; }
function attr (el, name) { return el.getAttribute(name) }
function tonum (x) { var n = parseFloat(x); return isNaN(n) ? null : n }
function kill (el) { el.parentNode.removeChild(el) }
function posf (f, a) { for (var i=0; i < a.length; i++) { if (f(a[i])) return i; } return -1; }
function pos (x, a) { return (typeof x == 'function') ? posf(x,a) : Array.prototype.indexOf.call(a,x) }
function find (x, a) { var i = pos(x, a); return (i >= 0) ? a[i] : null; }
function keep (fn, a) { return Array.prototype.filter.call(a, fn) }
function cut (a, m, n) { return Array.prototype.slice.call(a, m, n) }
function each (fn, a) { return Array.prototype.forEach.call(a, fn) }
function map (fn, a) { return Array.prototype.map.call(a, fn) }
function rem (a, x) { var i = pos(x, a); if (i >= 0) { a.splice(i, 1); } return a; }
function last (a) { return a[a.length - 1] }
function vis(el, on) { if (el) { on ? remClass(el, 'nosee') : addClass(el, 'nosee') } }
function noshow (el) { addClass(el, 'noshow') }
function show (el) { remClass(el, 'noshow') }
function ind (el) { return (byTag(el, 'img')[0] || {}).width }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment