Difference between revisions of "M.js"
Jump to navigation
Jump to search
Line 1: | Line 1: | ||
Some handy functions for every day JavaScript | |||
/* returns a new element for a given tag with properties and children */ | /* returns a new element for a given tag with properties and children */ | ||
function $m(tag,props,children){ | function $m(tag,props,children){ | ||
let args = [...arguments]; | let args = [...arguments]; |
Latest revision as of 14:53, 19 November 2023
Some handy functions for every day JavaScript
/* returns a new element for a given tag with properties and children */ function $m(tag,props,children){ let args = [...arguments]; let ret = document.createElement(args.shift()); for(let a of args){ if (typeof a === "string") ret.innerHTML = a; else if (Array.isArray(a)){ for(let c of a){ if (typeof c === 'string'){ ret.appendChild(document.createTextNode(c)) }else{ ret.appendChild(c); } } }else{ for(let k in a){ if (k === 'text'){ ret.innerText = a[k]; }else if (k.startsWith('on')) ret.addEventListener(k.substring(2),a[k]); else ret.setAttribute(k,props[k]); } } } return ret; } /* renaming */ let $i = id => document.getElementById(id); /* querySelectorAll as a list */ let $q = (p,context) => Array.from((context||document).querySelectorAll(p)); /* returns a copy sorted by key function f */ function sort(ls,f){ let ret = [...ls]; if (f===undefined){ ret.sort(); }else{ ret.sort((a,b)=>f(a)>=f(b)); } return ret; } /* like python... returns a list of integers */ let range = n => [...new Array(n)].map((_,i)=>i);