Design & Download
Your JS Library
in Seconds!!!

Snippet: dom() - Write HTML in JS

Written by Christopher West (cwest) on November 29, 2015.
Turns an object or an HTML string into DOM nodes.
var dom;
(function(RGX_DASH, INNER_TEXT, TEXT_CONTENT, STRING, PROP_HASH) {
  function capAfterDash(m, afterDash) {
    return afterDash.toUpperCase();
  }
  dom = function(obj) {
    var elem, propName, propValue, i, l, j, c, style, stylePropName, kids;
    if (typeOf(obj, STRING)) {
      elem = slice(dom({ _: 'DIV', html: obj }).childNodes);
    }
    else {
      elem = document.createElement(obj.nodeName || obj._);
      for (propName in obj) {
        propValue = obj[propName];
        if (has(obj, propName) && (propName = PROP_HASH[propName] || propName) != '_') {
          if (propName == 'style') {
            style = elem[propName];
            if (typeOf(propValue, STRING)) {
              style.cssText = propValue;
            }
            else {
              for (stylePropName in propValue) {
                if (has(propValue, stylePropName)) {
                  style[stylePropName.replace(RGX_DASH, capAfterDash)] = propValue[stylePropName];
                }
              }
            }
          }
          else if (propName == INNER_TEXT || propName == TEXT_CONTENT) {
            elem[TEXT_CONTENT] = elem[INNER_TEXT] = propValue;
          }
          else if (propName == '$') {
            propValue = toArray(propValue);
            for (i = 0, l = propValue.length; i < l;) {
              for (kids = toArray(dom(propValue[i++])), j = 0, c = kids.length; j < c;) {
                elem.appendChild(kids[j++]);
              }
            }
          }
          else if (/\W/.test(propName)) {
            elem.setAttribute(propName, propValue);
          }
          else {
            elem[propName] = propValue;
          }
        }
      }
    }
    return elem;
  };
})(/-([^-])/g, 'innerText', 'textContent', 'String',
  {nodeName:'_',html:'innerHTML',text:'innerText',children:'$','for':'htmlFor','class':'className',cls:'className'});

dom() API Documentation

Description

Turns an object or an HTML string into DOM nodes.

Parameters

  1. obj {Object|String}:
    If a string is specified it will be interpreted as HTML and the corresponding DOM nodes will be returned in an array. If an object is specified it must at least have the nodeName property specified. In order to specify the style attribute, you can specify the style property as a string or an object of style properties. In order to set the text of the element you can define either the innerText property or the textContent property. Add a children property as an array to the object to specify one or more child nodes. Each item in the array should either be string or an object to be recursively interpreted by YourJS.dom(). If children is just an object or a string it will be wrapped with an array.

Returns

Returns one or more DOM nodes which represent obj.