user1477388
user1477388

Reputation: 21430

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?

Upvotes: 0

Views: 4828

Answers (3)

user7181498
user7181498

Reputation:

Should you need to target a class instead of a element id, I found the following to be and effective and easy to maintain method:

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

Given it is always better to target an id instead of a class, but in cases when you are relying on outside libraries that isn't always viable.

Upvotes: 1

BuffaloBuffalo
BuffaloBuffalo

Reputation: 7852

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

Upvotes: 1

user1477388
user1477388

Reputation: 21430

The way I did it was this (I am open to any other solutions):

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

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

Upvotes: 0

Related Questions