Search code examples
javascriptjqueryhtmlclone

clone div's children using javascript


Im cloning a div multiple times and I need to change its inner children div's as well. (e.g. id_j1, id_j2 etc.)

I manage to clone the whole div and change its id but not the children's ids.

javascript

document.getElementById('btn_new_service').onclick = duplicate;
var i =0;
function duplicate() {
    var original = document.getElementById('duplicator');
    var clone = original.cloneNode(true); // "deep" clone
    clone.id = "duplicator" + ++i; // there can only be one element with an ID} 
original.parentNode.appendChild(clone);

if i append the code below in the above code then i get an error of Uncaught TypeError: clone.children is not a function.

var new_div_ID = 'duplicator-' + i;
var new_service_ID = 'c_service-'+i;
var new_vat_ID = 'vat-'+i;
var new_amount_ID = 'amount-'+i;
var new_vatamount_ID = 'vat_amount-'+i;
clone.children('#c_service').attr('id',new_service_ID);
clone.children('#vat').attr('id',new_vat_ID);
clone.children('#amount').attr('id',new_amount_ID);
clone.children('#vat_amount').attr('id',new_vatamount_ID);

i took both of them from 2 different code snippets which they were working fine but when i combine them only they don't. Any tips why does that happens?


Solution

  • if i append the code below in the above code then i get an error of Uncaught TypeError: clone.children is not a function.

    children is not a function in vanila js, use querySelector instead and setAttribute instead

    Make it

    clone.querySelector('#c_service').setAttribute('id',new_service_ID);