JavaScript: Creating Nodes, Functional Programing Style

By Xah Lee. Date: . Last updated: .

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;


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 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
  ((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(),

  (x) => {
    const xli = document.createElement("li");
    xli.innerHTML = x;

// insert the new node into document

here's the pure functional programing style with no temp variables.

  ((xel, xitems) => {
      (xinner) => {
        ((xli, xbb) => {
          xli.innerHTML = xbb;
        })(document.createElement("li"), xinner);
    return xel;
      "<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.

JavaScript in Depth