HTML.js
Simple runtime HTML DOM node creation. HTMLDocument, document in Internet Explorer, is extended with a createHTML function that can create a complete node graph with a single call.
The benefit over the using the standard document.createElement might not be obvious. Well, Internet Explorer will cause problems, it can’t assign/change the type and name attributes after creation for tags like INPUT. It also have a buggy setAttribute implementation which wrongly assigns the JavaScript properties instead of the text value for the attribute. Many use innerHTML to create and append nodes, that also has it’s problems. You’ll need to escape all the XML characters (&"<>) for attributes values and text node content, and Internet Explorer can’t append things like OPTION’s to SELECT tags using innerHTML.
Warning! I've noticed that when creating TABLE without TBODY in Internet Explorer it doesn't render when appended to document. So always add TBODY to your tables.
The document.createHTML function accepts multiple argument syntaxes:
- To create an
Element, use the following arguments:- The name of the tag to create,
tagName. - Initial attribute key/values as an
Object. Optional if theArrayof children is supplied, see argument 3. - An
Arraywith child nodes to append, in the same syntax as described. Optional if the attributesObjectis supplied, see argument 2.
- The name of the tag to create,
- To create a
TextNodejust supply astringwithout attributesObjector childrenArray. - Any existing
Nodesupplied is first removed from it’s parent then appended.
Any of the above argument combinations can be used multiple times, creating a list of nodes, returned as a DocumentFragment.
var json = ['A',{href:'http://llamalab.com'},['LlamaLab']];
var llamalab = document.toHTML.apply(document, json);
document.body.appendChild(document.createHTML(
'H4',['Links'],
'UL',[
'LI',llamalab,
'LI',['A',{href:'http://slashdot.org'},['Slashdot']],
'LI',[document.getElementById('moveThisLink')],
]
));
Further examples can be found here.
Documentation
The generated online documentation can be found here.
Changelog
- 2008-12-03 v0.1: Initial public release.
Download
License
GNU Lesser General Public License <http://www.gnu.org/licenses/lgpl-3.0.txt>
Author
Henrik Lindqvist <henrik.lindqvist@llamalab.com>