1
    //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
1

1 Answer 1

6

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 createElement in raw JS to create a new one):

$(function () {
    // element to be cloned
    var _clone_me = $('#toBeCloned');
    // 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 = _clone_me.clone(true); // clone copy
        _newElm.find('span').html(data);  //edit content of span
        _target.append(_newElm); //update target
    });
});

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 way append works actually moves the object, so you weren't getting duplicate objects.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.