-2

I have div element and have a class for it. I want to create multiple div using that class, but I don't 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. I 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)
  }       
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Nikil
  • 99
  • 15

1 Answers1

0

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>
user3297291
  • 22,592
  • 4
  • 29
  • 45
  • @thanks for your time,but my condition i cant use lik it,i need use insertAfter or InsertBefore ,so i want to use jquery inside it – Nikil Oct 21 '16 at 08:10