Use Builder to easily create DOM elements dynamically.
script.aculo.us V1.5 and later.
Builder.node( elementName ) Builder.node( elementName, attributes ) Builder.node( elementName, children ) Builder.node( elementName, attributes, children )
elementNamestring The tag name for the element.attributesobject Typical attributes areid,className,style,onclick, etc.childrenarray List of other nodes to be appended as children.
If an element of the children array is plain text or numeric, it will be automatically appended as a text node.
Instead of an array, children can also be a Java Script String or numeric, to ease usage.
class: When specifying the class attribute for the node, use className to circumvent a Firefox bug.for: To set a for attribute (in labels) use htmlFor, since ‘for’ is a reserved word in javascript.
table = Builder.node('table', {width:'100%',cellpadding:'2',cellspacing:'0',border:'0'});
tbody = Builder.node('tbody');
tr = Builder.node('tr',{className:'header'});
td = Builder.node('td',[ Builder.node('strong','Category')]);
tr.appendChild(td);
tbody.appendChild(tr);
table.appendChild(tbody);
$('divCat').appendChild(table);
You can also combine them but you need to make sure you create the tbody tag or it will not work in IE. I have tested this in FF 1.5 and IE 6. I dont have access to other browsers. The one problem that I have found is that with TR and TD elements you can not put a style tag on them as it just makes IE stop doing the Builder Function.
element = Builder.node('p',{className:'error'},'An error has occurred');
creates following element:
<p class="error">An error has occured</p>
element = Builder.node('div',{id:'ghosttrain'},[
Builder.node('div',{className:'controls',style:'font-size:11px'},[
Builder.node('h1','Ghost Train'),
"testtext", 2, 3, 4,
Builder.node('ul',[
Builder.node('li',{className:'active', onclick:'test()'},'Record')
]),
]),
]);
creates (without newlines):
<div id="ghosttrain">
<div class="controls" style="font-size:11px">
<h1>Ghost Train</h1>
testtext234
<ul>
<li class="active" onclick="test()">Record</li>
</ul>
</div>
</div>
In javascript code, if you want to use your new element, you can add it to an existing dom element by calling
$('myExistingDomElement').appendChild(element);
If you want to be able to call any of prototype’s extension-methods on the created node, then you need to pass it through the $() function:
var new_el = Builder.node('div',{id:'some_id'});
new_el = $(new_el);
new_el.hide();
There is also the XML/HTML JavaScript extension that allows similar functionality, but with a slightly easier syntax. This extension allows you to do things like html.div({id:'mydiv},"Here is the content: ", html.span("content")).