Login Register

dynamic widget creation

(editor: moving to the appropriate forum...)

How can I create a widget programatically in a container which doesn't exist ?
for example i tried:
var d = document.createElement("div");
var widget = new dijit.form.Button({}, d);
// container is a reference to an existing div on the page
container.addChild(d);
widget.startup();
Unfortunatly it doesn't work..

create a button in a new

create a button in a new div:

var div = dojo.doc.createElement('div');
// append it to the body
dojo.body().appendChild(div);
// create a button
var button = new dijit.form.Button({ label:"foo" });
// append it to the div, addChild is a layout widget method, nothing to do with dom stuff:
// you want appendChild 
div.appendChild(button.domNode);
button.startup();

you can do it backwards, too by passing a node as a reference for your button

var div = dojo.doc.createElement('div');
dojo.body().appendChild(div);
var buttonNode = dojo.doc.createElement('div');
div.appendChild(buttonNode);
// now the widget stuff:
var button = new dijit.form.Button({ label: "foo" },buttonNode);
button.startup();

both should have the same results, though are different techniques based on how you want to manipulate the dom. I prefer to know where my nodes are and use the srcNodeRef (2rd param to new someDijit(...) ) over letting a widget create it's own node. either way, the node being used for the dijit can be accessed as .domNode always.

Using the parser

Thanks dante ;)
Actually I found another way to do it using the parser.
var resultDiv = dojo.byId("container");
resultDiv.innerHTML = "";
dojo.parser.parse(resultDiv);