JS: Creating Nodes, Functional Programing Style
When coding JavaScript, often you need to create html elements by using ele.innerHTML = …
The problem is that it forces you to declare variables. Is it possible to write it without variables? In a pure functional programing style?
For example, normally you'd do this:
// your are given a html text, myInner const myInner = "<p id='xyz' class='abc'>complicated html <b>stuff</b> here<p>"; // you need to wrap it with a div, and attach it to the document const newNode = document.createElement("div"); newNode.innerHTML = myInner; document.body.appendChild(newNode);
You see that it involves a new var “newNode”.
Is it possible not to create a var?
it'd be great if one can do this:
document.body.appendChild(document.createElement("div").innerHTML = myInner);
but the problem is that the obj.innerHTML = string
does not return the object obj. It returns the string.
Solution
Solution is to use a anonymous function wrapper and eval it inplace.
const xInnerHTML = "<p id='xyz' class='abc'>complicated html <b>stuff</b> here<p>"; // pure functional programing, no variable document.body.appendChild( ((xele, xinnerStr) => { xele.innerHTML = xinnerStr; return xele; })(document.createElement("div"), xInnerHTML), );
Real World Example
Here is a more complicated example.
Here is the normal way, with lots temp variables.
const xnewEl = document.createElement("ul"); const xitems = [ "<b>platform:</b> " + navigator.platform, "<b>cookieEnabled:</b> " + navigator.cookieEnabled, "<b>javaEnabled:</b> " + navigator.javaEnabled(), ]; xitems.forEach( (x) => { const xli = document.createElement("li"); xli.innerHTML = x; xnewEl.appendChild(xli); }, ); // insert the new node into document document.body.appendChild(xnewEl);
here's the pure functional programing style with no temp variables.
document.body.appendChild( ((xel, xitems) => { xitems.forEach( (xinner) => { ((xli, xbb) => { xli.innerHTML = xbb; xel.appendChild(xli); })(document.createElement("li"), xinner); }, ); return xel; })( document.createElement("ul"), [ "<b>platform:</b> " + navigator.platform, "<b>cookieEnabled:</b> " + navigator.cookieEnabled, "<b>javaEnabled:</b> " + navigator.javaEnabled(), ], ), );
You can copy and paste the code to the browser console, and see element attached at end of the this page.