//dom
<div id='toBeCloned'><span>Some name</span></div>
<div id='targetElm'></div>
//js
$(function () {
//creating a clone
var _clone = $('#toBeCloned').clone(true);
// target element
var _target = $('#targetElm');
//now target element is to be filled with cloned element with data of span changed
var _someData = [1, 2, 3, 4];
//loop through data
$.each(_someData, function (i, data) {
var _newElm = {};
$.extend(_newElm, _clone);//copy cloned to new Elm
_newElm.find('span').html(data); //edit content of span
alert('p'); // alert added to show that append in next line inspite of adding new element to dom just updating the previous one
_target.append(_newElm);//update target
});
});
expected Result:
1 2 3 4
resut iam getting is
4
//dom <div id=’toBeCloned’><span>Some name</span></div> <div id=’targetElm’></div> //js $(function () { //creating a clone var
Share
You just want to clone the element on each iteration. A DOM object is not a normal JS object (Well it is, but it has more to it which is why you have to use
createElementin raw JS to create a new one):Why your code failed, is though you were “extending” an empty object on each iteration, it was still always referring to the same DOM node. You kept changing its value, and appending it to
#target. Additionally, the wayappendworks actually moves the object, so you weren’t getting duplicate objects.