Skip to content

Instantly share code, notes, and snippets.

@thiagoh
Last active April 21, 2019 17:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thiagoh/a6d3a4f9cdf762e99b5e6f7c6f8f5b5c to your computer and use it in GitHub Desktop.
Save thiagoh/a6d3a4f9cdf762e99b5e6f7c6f8f5b5c to your computer and use it in GitHub Desktop.
lite DOM manipulator
'use strict';
function $(el) {
function $Element() {
const self = this;
this.$is$ = function $is$() {
return true;
};
this.style = function style(key, value) {
if (/(left|right|top|bottom|background-position-x|background-position-y)/i.test(key)) {
value = typeof value === 'number' ? `${value}px` : value;
}
if (typeof key !== 'undefined') {
if (typeof value === 'undefined') {
return el.style[key];
}
console.log(`style[${key}] => ${value}`);
el.style[key] = value;
}
return self;
};
this.html = function html(html) {
if (typeof html !== 'undefined') {
el.innerHTML = html;
}
return self;
};
this.addClass = function addClass(className) {
if (typeof className === 'string') {
el.className = el.className + ' ' + className;
}
return self;
};
this.removeClass = function removeClass(className) {
if (typeof className === 'string') {
el.className = el.className.replace(new RegExp(className), 'gi');
}
return self;
};
this.htmlAppend = function html(html) {
if (typeof html === 'undefined') {
return el.innerHTML;
}
self.html(el.innerHTML + html);
return self;
};
Object.defineProperty(this, 'element', {
get: function get() {
return el;
},
});
}
return new $Element(el);
}
/**
* $.style('opacity', 0.2); // [$]
* $.style('opacity'); // 0.2
*/
const filteredFns = ['style', '$is$'];
const fns = Object.keys($())
function $(selector) {
const $ElementArray =
Array.prototype.slice.call(document.querySelectorAll(selector))
.map(node => $(node));
fns.forEach(fn => {
$ElementArray[fn] = function () {
const args = Array.prototype.slice.call(arguments);
const output = $ElementArray.map($Element => $Element[fn].apply($Element, args));
if (filteredFns.indexOf(fn) >= 0) {
if (output.length === 1) {
return output[0];
}
}
return $ElementArray;
};
});
return $ElementArray;
}
window.$ = $;
export default $;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment