Search code examples
javascriptclone

Is it possible to use cloneNode to clone multiple divs?


I'm trying to clone to divs in and append them to to other divs (their parents). I'm using clonenode for this but it doesn't seem to work. It clones the div in the first function and appends it to the parent of the div in the second function! Not sure what I'm doing wrong. Here's the code (*EDIT:*var added):

function cloneQ() {
    //Cloning questions and shit
    cloneQ.id = (cloneQ.id || 0) + 1;
    var question = document.getElementById("question");
    var clone = question.cloneNode(true);
    var numberOfQuestions = $('.question').length;
    var id = "questioncon" + cloneQ.id;
    clone.id = id;
    question.parentNode.appendChild(clone);
    var inid = "question" + cloneQ.id;
    var optionid = "optionsdiv" + cloneQ.id;
    $('#' + id + ' ' + '.' + 'questionin').attr('id', inid);
    $('#' + id + ' ' + '.' + 'options').attr('id', optionid);
    $('#' + id + ' h2').html('Question ' + cloneQ.id);

    //Question Cloned
    }

function cloneforPrint() {
    cloneforPrint.id = (cloneforPrint.id || 0) + 1;
    var questionprint = document.getElementById("questionprint");
    var cloneprint = questionprint.cloneNode(true);
    var printid = "questionprint" + cloneforPrint.id;
    cloneprint.id = printid;
    questionprint.parentNode.appendChild(clone);
    var printinid = "thequestionprint" + cloneforPrint.id;
    $('#' + printid + ' ' + '.' + 'thequestionprint').attr('id', printinid);
}

LIVE here: http://bit.ly/R8hB2m


Solution

  • Edit : Global vars are the problem.

    You aren't putting var in front of your variables, making them global. The cloneForPrint function is picking up vars defined in cloneQ.

    Init all the variables properly and you'll get some errors indicating where the problems are.

    CloneQ is indeed appending to questions parent, but cloneForPrint then moves it somewhere else.

    -- Old answer --

    There's not enough here to work out what the problem is. My 1st guess is that the question element has the same parent as the questionprint element.

    Based on the code given, cloneQ should definitely append to questions parent. So to give the appearance you've specified the DOM probably doesn't look like what you expect.