Builder |
Use Builder to easily create DOM elements dynamically.
Availability
script.aculo.us V1.5 and later.
Synopsis
Builder.node( elementName ) Builder.node( elementName, attributes ) Builder.node( elementName, children ) Builder.node( elementName, attributes, 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.
Special cases
Examples
Creating TR and TD elements
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.
Simple Example
var element = Builder.node('p',{className:'error'},'An error has occurred');
creates following element:
<p class="error">An error has occured</p>
Complex Example
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>
Usage
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();
|