Updated: Added functionality for text node creation: Just pass in node type as 'textnode' and then the second argument is your text, defaults to
if omitted.
Updated: Now you can use it to add styles or attributes to an existing node. Just pass in the node (instead of a type of node).
// Generic Create Element, $X, exNihilo() R.E.M. 2006
// Creates element and/or adds attributes to node and/or adds styles to node
var exNihilo = $X =function (el,attributes,styles) {
if (el==='textnode')
{ return document.createTextNode(((attributes)? attributes:' ')); }
var node=(el.constructor==String)?document.createElement(el): el,arg;
if (attributes){for (arg in attributes){node[arg]=attributes[arg];} }
if (styles) {for (arg in styles) {node.style[arg]= styles[arg];} }
return node;
}
You can call it with some code like this:var node=exNihilo( 'span',
{innerHTML:'hello World'},
{border:'2px solid red',padding:'20px'} )
document.body.appendChild(node);
To add styles or attributes to existing nodes, pass in a node[element] instead of nodeType[string]:
// change/add color style of node
$X(node,0,{color:'#ff0000'})