Nikil Nikil - 1 month ago 13
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
$element.append(DivHtml(lastId,parentclassName));
},
};

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

Answer

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) {
   elements.push({
     className: className,
     id: idPrefix + i
   });
};

ko.applyBindings({items: elements });
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>


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