3

Is it possible to create Onsen UI elements dynamically using JavaScript? The official documentation says nothing about it.

Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
Anina
  • 453
  • 3
  • 18

2 Answers2

7

You can create dynamically Onsen UUI elements by using ons._util.createElement() function. It takes, in input, the HTML code you want to generate. For example:

var button = ons._util.createElement("<ons-button></ons-button>");
document.body.appendChild(button);

It will create a ons-button element, and append it to the body.

EDIT

You can also create it in an alternative way:

var div = document.createElement('div');
div.innerHTML = '<ons-button></ons-button>'
document.body.appendChild(div);
Andi Pavllo
  • 2,506
  • 4
  • 18
  • 30
  • @Amina to use it you need to use onsen ui latest version from GitHub: [download](https://github.com/OnsenUI/OnsenUI/archive/master.zip). I also updated my answer with an alternative way to do it. – Andi Pavllo Jul 17 '15 at 13:04
0
var content = document.getElementById("my-content");
    content.innerHTML="<ons-button>Another Button</ons-button>";
    ons.compile(content);

with this in you html

<div id="my-content"></div>
Anina
  • 453
  • 3
  • 18
  • Your answer doesn't provide any further information to the one previously posted. Anyway, modifying directly the innerHTML con the `my-content` element, will overwrite the previous content. Moreover, `ons.compile()` method will be called automatically called after appending the element to the DOM – Andi Pavllo Aug 04 '15 at 07:58
  • yeah but you will need to call it if you want to modify the element after appending it to the DOM. it will be called for you once and then you'll need to call it yourself. Correct me if i'am wrong – Anina Aug 04 '15 at 08:08
  • It depends on what you are modifying, most part of the attributes can be added and removed dynamically, without any need of calling `ons.compile()`. – Andi Pavllo Aug 04 '15 at 08:47