mirror of
https://github.com/arfct/itty-bitty.git
synced 2026-03-11 08:54:33 +00:00
Create util.js
This commit is contained in:
parent
dfb949ab93
commit
0844d64d1a
1 changed files with 32 additions and 0 deletions
32
docs/js/util.js
Normal file
32
docs/js/util.js
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
const m = (selector, ...args) => {
|
||||
var attrs = (args[0] && typeof args[0] === 'object' && !Array.isArray(args[0]) && !(args[0] instanceof HTMLElement)) ? args.shift() : {};
|
||||
|
||||
let classes = selector.split(".");
|
||||
if (classes.length > 0) selector = classes.shift();
|
||||
if (classes.length) attrs.className = classes.join(" ")
|
||||
|
||||
let id = selector.split("#");
|
||||
if (id.length > 0) selector = id.shift();
|
||||
if (id.length) attrs.id = id[0];
|
||||
|
||||
var node = document.createElement(selector.length > 0 ? selector : "div");
|
||||
for (let prop in attrs) {
|
||||
if (attrs.hasOwnProperty(prop) && attrs[prop] != undefined) {
|
||||
if (prop.indexOf("data-") == 0) {
|
||||
let dataProp = prop.substring(5).replace(/-([a-z])/g, function(g) { return g[1].toUpperCase(); });
|
||||
node.dataset[dataProp] = attrs[prop];
|
||||
} else {
|
||||
node[prop] = attrs[prop];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const append = (child) => {
|
||||
if (Array.isArray(child)) return child.forEach(append);
|
||||
if (typeof child == "string") child = document.createTextNode(child);
|
||||
if (child) node.appendChild(child);
|
||||
};
|
||||
args.forEach(append);
|
||||
|
||||
return node;
|
||||
};
|
||||
Loading…
Reference in a new issue