Create DOM Structure

From GreaseSpot
Jump to: navigation, search

A variety of approaches exist to turn a Javascript object into a DOM structure, without calling all of the .createElement()s and .appendChild()s by hand.

One Node, With Attributes

function createElement(type, attributes){
  var node = document.createElement(type);
  for (var attr in attributes) if (attributes.hasOwnProperty(attr)){
    node.setAttribute(attr, attributes[attr]);
  }
  return node;
}

Usage:

var styles = createElement('link', {rel: 'stylesheet', type: 'text/css', href: 'style.css'});
document.body.appendChild(styles);

Advanced, Nested Element Creation

Creates an element with attributes as well as child elements with their own attributes and children.

The first parameter should be an object like:

{n: nodename, a: {attr1: val, attr2: val}, c: [child1, child2], evl: {type: eventlistener_type, f: eventlistener_function, bubble: bool}}

Where child1 and child2 are objects of similar structure.

function createEl(elObj, parent) {
  var el;
  if (typeof elObj == 'string') {
     el = document.createTextNode(elObj);
  }
  else {
     el = document.createElement(elObj.n);
     if (elObj.a) {
        attributes = elObj.a;
        for (var key in attributes) if (attributes.hasOwnProperty(key)) {
           if (key.charAt(0) == '@')
              el.setAttribute(key.substring(1), attributes[key]);
           else 
              el[key] = attributes[key];
        }
     }
     if (elObj.evl) {
        el.addEventListener(elObj.evl.type, elObj.evl.f, elObj.evl.bubble);
     }
     if (elObj.c) {
        elObj.c.forEach(function (v, i, a) { createEl(v, el); });
     }
  }
  if (parent)
     parent.appendChild(el);
  return el;
}

Example usage:

createEl({n: 'ol', a: {'@class': 'some_list', '@id': 'my_list'}, c: [
{n: 'li', a: {textContent: 'first point'}, evl: {type: 'click', f: function() {alert('first point');}, bubble: true}},
{n: 'li', a: {textContent: 'second point'}},
{n: 'li', a: {textContent: 'third point'}}
]}, document.body);
Personal tools