Created
April 30, 2009 05:44
-
-
Save rgrove/104286 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
YAHOO.namespace('util').HTML = (function () { | |
var d = document, | |
Y = YAHOO, | |
isArray = Y.lang.isArray, | |
isObject = Y.lang.isObject, | |
isString = Y.lang.isString, | |
ATTRIBUTES = !d.documentElement.hasAttribute ? { | |
// IE < 8 | |
'for' : 'htmlFor', | |
'class': 'className' | |
} : { | |
// W3C | |
'htmlFor' : 'for', | |
'className': 'class' | |
}, | |
self; | |
// -- Private Methods ------------------------------------------------------ | |
function resolve(f) { | |
while (Y.lang.isFunction(f)) { | |
f = f.call(); | |
} | |
return f; | |
} | |
function setAttribute(el, name, value) { | |
el.setAttribute(ATTRIBUTES[name] || name, value); | |
} | |
// -- Public Methods ------------------------------------------------------- | |
self = { | |
element: function (name) { | |
var el = d.createElement(name), | |
arg, i, key, len, value; | |
for (i = 1, len = arguments.length; i < len; ++i) { | |
arg = resolve(arguments[i]); | |
if (arg === false) { | |
continue; | |
} | |
if (isObject(arg) && !isArray(arg)) { | |
// Objects are attribute maps. | |
for (key in arg) { | |
if (arg.hasOwnProperty(key)) { | |
value = resolve(arg[key]); | |
if (value === false) { | |
continue; | |
} | |
setAttribute(el, key, value); | |
} | |
} | |
} else { | |
// Everything else is a node (or can become a node) and goes | |
// into a fragment. | |
el.appendChild(self.fragment(arg)); | |
} | |
} | |
return el; | |
}, | |
fragment: function (nodes, fragment) { | |
var i, node, len; | |
fragment = fragment || d.createDocumentFragment(); | |
nodes = Y.lang.isArray(nodes) ? nodes : [nodes || false]; | |
for (i = 0, len = nodes.length; i < len; ++i) { | |
node = resolve(nodes[i]); | |
if (node === false) { | |
continue; | |
} | |
if (node && node.nodeType) { | |
fragment.appendChild(node); | |
} else if (isString(node)) { | |
fragment.appendChild(d.createTextNode(node)); | |
} else if (isArray(node)) { | |
self.fragment(node, fragment); | |
} | |
} | |
return fragment; | |
}, | |
html: function () { | |
var tmp = d.createElement('div'); | |
tmp.appendChild(self.fragment(Array.prototype.slice.call(arguments))); | |
return tmp.innerHTML; | |
} | |
}; | |
// Aliases. | |
self.el = self.element; | |
self.frag = self.fragment; | |
return self; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment