JS: 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;

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 myInner = "<p id='xyz' class='abc'>complicated html <b>stuff</b> here<p>";

// pure functional programing, no variable
document .body.appendChild(
    (function (ele,inn) {
        ele.innerHTML = inn;
        return ele;
    })(document .createElement("div"), myInner)
);

Real World Example

Here's a more complicated example.

Here's the normal way, with lots temp variables.

const newNode = document .createElement("ul");

const items = [
    "<b>platform:</b> " + navigator.platform,
    "<b>cookieEnabled:</b> " + navigator.cookieEnabled,
    "<b>javaEnabled:</b> " + navigator.javaEnabled(),
];

items.forEach(
    function (x) {
        const liNode = document .createElement("li");
        liNode.innerHTML = x;
        newNode.appendChild(liNode);
    }
);

// insert the new node into document
document .body.appendChild(newNode);

here's the pure functional programing style code.

document .body.appendChild(
    (function (ul, array) {
        array.forEach(
            function (inner) {
                (function (li,bb) {
                    li.innerHTML = bb;
                    ul.appendChild(li);
                })(document .createElement("li"),inner)
            }
        );
        return ul; })(
        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.

Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Object Ref
  5. DOM Scripting
  6. SVG
  7. Blog