user1477388 user1477388 - 3 months ago 23
HTML Question

Create element inside of parent element in Dojo

I can create a

div
inside the body like so:

var n = dojo.create("div", { innerHTML: "<p>helloWorld</p>" }, dojo.body());


I would like to create a
div
inside of my parent element such as this:

<div id="parent"></div>


I have tried this but it doesn't seem to work:

var n = dojo.create("div", { innerHTML: "<p>helloWorld</p>" }, dojo.query('#parent'));


How can I create my
div
inside of my parent
div
which already exists in the DOM?

Answer

The solution you posted is entirely valid. A couple of alternatives:

No need to look up the dom node, you can pass in a String (the id of the node)

require(["dojo/dom-construct"], function(domConstruct){
  var n = domConstruct.create("div", { innerHTML: "<p>helloWorld</p>" }, 'parent');
});

Or you could construct the node and place it later using domConstruct#place:

require(["dojo/dom-construct"], function(domConstruct){
  var n = domConstruct.create("div", { innerHTML: "<p>helloWorld</p>" });
  domConstruct.place(n, 'parent');
});

domConstruct#place can also take an optional position parameter. The API Docs have more information on it