javascript utility for creating DOM trees from arrays.
Go to file
2023-07-16 16:43:48 +02:00
src change import paths from absolute to relative. 2023-07-16 16:41:50 +02:00
export.mjs change import paths from absolute to relative. 2023-07-16 16:41:50 +02:00 edit readme. 2023-07-16 15:40:57 +02:00

small utility for creating DOM trees from javascript arrays.

note that this doesn't actually take a json string, but rather an actual array, as input. array_as_html would be a bit inaccurate though, since it also handles some other things such as functions and strings in ways that make sense.

to use, clone/submodule/subtree/whatever the main branch, and import json_as_html from export.mjs.

to see a demo, or contribute, clone the dev branch.


here's the demo array being used at the time of writing this:

		["id", "wrapper"],
		["class", "demo_div"],
		["h1", [], "header :)"],
		["p", [], "paragraph! meow"],
		["p", [], "another paragraph!! this is so cool"],
		state => ["button", [
			["onclick", _ => {
				state.set("clicked", true);
		], "it can even do buttons!"],
		state => ["p", [], state.get("clicked") ? "clicked" : "not clicked"],

it assumes a function render which replaces the contents of the <body> with the result of calling json_as_html with this array as argument. it also assumes a Map called state.

how to use

the json_as_html function takes two arguments:

  1. a required json argument that gets transformed into a tree of Nodes.
  2. an optional state argument which defaults to an empty Map.

this is how the function returns, given certain types of json input:

  • Node object: return it as it is.
  • string: return a text node containing the string.
  • function: evaluate the function, with state as argument, and recursively call json_as_html on the result. return what that recursive call returns.
  • array: see below.

when given an array as json input, the function treats its elements as the tag name, attributes, and children, of the Node to create, in that order. call these type, attributes, and children:

  • type is expected to be a string.
  • attributes is expected to be an array, where each element is a key-value pair.
  • children is expected to be an array containing valid inputs for json_as_html. if it's not an array, it's treated as an array containing a single element.

both attributes and children default to empty arrays, and may thus be omitted.