Nikil Nikil - 1 year ago 92
HTML Question

creating the multiple div dynamically using javascript

i have div element and have a class for it,i want to create multiple div using that class,but i dont want to create nested div,i want to create div outside using javascript,i used append property,but its create nested div below is html as i required need help

//have this div
<div data-bind="dynamicDiv" class="one"></div>

//need to create multiple div

//Knockoutjs && javascript//

ko.bindingHandlers.dynamicDiv = {
init: function (element, valueAccessor) {
var parentclassName = element.className;
lastId += 1;

///it is creating nested div, want to create outside of parentclass not inside the parent class

function DivHtml(lastId,parentclassName) {
Newdiv = document.createElement('div'); = "divId_"+lastId
document.querySelector("." + parentclassName).appendChild(Newdiv)

Answer Source

Fixes for your current code:

  • In DivHtml, the third line should be return NewDiv
  • init should append to element.parentElement using appendChild
  • You never define $element, it should be just element or $(element)

But even if you fix this, I don't understand what you're trying to achieve.

Your example doesn't really show why you'd need a custom binding handler for this. Seems to me that knockout's default bindings should suffice:

<div data-bind="attr: { id: 'divId_' + ++lastId }" class="one"></div>

If you need to copy the class name dynamically, I'd take care of that in a view model if I were you. Look in to the template and foreach bindings as well.

var className = "one";
var idPrefix = "divId_";
var nrOfElements = 5;
var elements = [];

for (var i = 0; i < nrOfElements; i += 1) {
     className: className,
     id: idPrefix + i

ko.applyBindings({items: elements });
<script src=""></script>

<div data-bind="foreach: elements">
  <div data-bind="attr: { id: id, 'class': className }, text: id"></div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download