Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
XT.js - DOM construction / templating library in 18 lines of JS, 323 bytes minified


Let's close the ultra-small library cycle with some awesome array-based templating. 323 bytes minified.

How to obtain

Just download the minified version here or include it into your code:

<script src="//"></script>


XT.js consists of just one function: XT(domStructure). The main feature of this function is that it returns a ready DocumentFragment instance ready to be inserted anywhere. The domStructure toplevel array must contain arrays only, and any internal array syntax is pretty straightforward:

  • the first array element is the tag name;
  • any scalar value (string or number) denotes element text content;
  • any object denotes element attributes in name-value form;
  • any array denotes the nested element of the same structure.

That's it.


The following code:

	['div', {'data-attr1': 23},
		['a', {href: ''}, 'Example text',
			['span', ' (additional span)']

will produce a DocumentFragment with the following HTML representation:

<div data-attr1="23">
	<a href="">Example text<span> (additional span)</span></a>

Update: for dynamic CSS rules construction, see XS.js.

!function(d) {
function nodeRender(tplArr, parent, k, o) {
for(;(o=tplArr.shift())!=null;) {
if(''+o === o || +o === o) //scalar
else if(''+o === '[object Object]') //object
for(k in o) parent.setAttribute(k, o[k])
else { //array
nodeRender(o, k = d.createElement(o.shift()))
window.XT = function(tplArr, docFrag) {
nodeRender(tplArr.slice(), docFrag = d.createDocumentFragment())
return docFrag
!function(d){function f(e,b,c,a){for(;null!=(a=e.shift());)if(""+a===a||+a===a)b.appendChild(d.createTextNode(a));else if("[object Object]"===""+a)for(c in a)b.setAttribute(c,a[c]);else f(a,c=d.createElement(a.shift())),b.appendChild(c)}window.XT=function(e,b){f(e.slice(),b=d.createDocumentFragment());return b}}(document)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.