M.js: Difference between revisions
		
		
		
		Jump to navigation
		Jump to search
		
 Created page with " let $i = id => document.getElementById(id);  let $q = (p,context) => Array.from((context||document).querySelectorAll(p));  function sort(ls,f){   let ret = [...ls];   if (f==..."  | 
				No edit summary  | 
				||
| Line 1: | Line 1: | ||
  /* returns a new element for a given tag with properties and children */  | |||
 /* Example use...  | |||
  document.body.append($m('div',{style:'border:solid;padding:1ex;'},[  | |||
   'This is a button ',  | |||
   $m('button',{onclick:()=>alert('Hello World')},'Say Hello')  | |||
  ]));  | |||
  function $m(tag,props,children){  |   function $m(tag,props,children){  | ||
   let args = [...arguments];  |    let args = [...arguments];  | ||
| Line 38: | Line 32: | ||
   return ret;  |    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);  | |||
Revision as of 14:46, 19 November 2023
/* returns a new element for a given tag with properties and children */
/* Example use...
document.body.append($m('div',{style:'border:solid;padding:1ex;'},[
  'This is a button ',
  $m('button',{onclick:()=>alert('Hello World')},'Say Hello')
]));
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);