User:Mike Dillon/Scripts/easydom.js

This is an old revision of this page, as edited by Mike Dillon (talk | contribs) at 00:16, 23 October 2006 (enhanced attribute support: skip null attribute values; invoke functions passed as attribute values). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
function createEasyDomFunction(name) {
    var stringType = typeof '';

    return function() {
        var elem = document.createElement(name);

        if (arguments.length == 0) return elem;

        var firstChild = 0;
        if (typeof arguments[0] != 'string'
            && typeof arguments[0].nodeType == 'undefined') {

            var attrs = arguments[0];
            for (var attrName in attrs) {
                var attrValue = attrs[attrName];
                // Skip null values
                if (attrValue == null) {
                    continue;
                }
                // Invoke functions and use their result as the value
                if (typeof(attrValue) == 'function') {
                    attrValue = attrValue();
                }
                // Set the attribute
                elem.setAttribute(attrName, attrValue);
            }
            firstChild = 1;
        }

        for (var i = firstChild; i < arguments.length; i++) {
            var child = arguments[i];
            if (typeof child == stringType) {
                child = document.createTextNode(child);
            }
            elem.appendChild(child);
        }

        return elem;
    };
}

var easyDomTags = [
    "script",
    "p",
    "a",
    "div", "span",
    "ul", "ol", "li",
    "img",
    "hr",
    "br",
    "em", "strong",
    "table", "tbody", "tr", "th", "td",
    "input",
    "h1", "h2", "h3", "h4", "h5"
];

var easyDom = {};
for (var i in easyDomTags) {
    easyDom[easyDomTags[i]] = createEasyDomFunction(easyDomTags[i]);
}
var easydom = easyDom;
var easyDOM = easyDom;