克隆div的孩子们使用javascript

问题描述:

我克隆了一个div多次,我需要改变它的内部孩子div。 (例如id_j1,id_j2等)克隆div的孩子们使用javascript

我设法克隆整个div并更改其ID而不是儿童ID。

的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); 

如果我在上面的代码下面的代码追加然后我得到的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); 

我把他们从两个不同的代码片段,他们工作正常,但是当我结合他们只有他们不。任何提示为什么发生这种情况?

+2

,它看起来像一个'的jQuery/DOMApi' meltin锅... – Hitmands

+1

' $(克隆).children('作为原生DOM元素不具备功能 – Satpal

+0

@Satpal我需要更改孩子的ID以及 – noel293

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不vanila的JS function,使用querySelector而不是和setAttribute代替

让它

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

感谢男人!这就像一个魅力,所以另一个wasn不工作,因为它不是一个内置的功能吗?我考虑过这个问题,但是因为最初的例子是声明一个变量clone并且使它等于主div,并且在它使用'children'来改变孩子的id之后 – noel293

+0

@ noel293'children'不是'Node的成员方法就像我在答案中提到的那样。这就是你得到这个错误的原因。 – gurvinder372