在javascript的不同外部div中替换相同的嵌套div



在使用javascript多次克隆div后,我正试图解决这个问题。我想用一个空的div来替换内部的div,每个div都有一个特定的id。假设我有:

<div id="original">
//some code here
<div id="problem">
//some code here
</div>
</div>
<div id="location">
//some code here
<div id="problem">
//some code here
</div>
</div>
<div id="rep">
//some code here
<div id="problem">
//some code here
</div>
</div>

我需要能够在div位置获得id有问题的div,并将其替换为与div存储库中的div相同的其他内容。

我试过

document.getElementById("location"),但它返回整个内容,我无法替换其中的特定div,如果我尝试document.getElementById("problem"),我无法指定需要哪个

您可以在标记上使用querySelector来获得与选择器匹配的第一个元素

你可以把它和结合起来

  • innerText/innerHTML直接修改内容
  • appendChild如果你在js部分创建了一个html结构

var locationDiv = document.getElementById('location');
var problemDiv = locationDiv.querySelector('#problem');
problemDiv.innerText = 'test';
<div id="original">
<div id="problem">
</div>
</div>
<div id="location">
<div id="problem">
</div>
</div>
<div id="rep">
<div id="problem">
</div>
</div>

最新更新