我想将我的第二个div插入或包装到另一个新的div容器中,但是它不是通过所有相同的类名应用的。请检查并告诉我所缺少的内容。
<div class="section" id="section1">
<div id="myDIV"> --> I want to wrap this into a new div
asdasd
</div>
</div>
<div class="section" id="section1">
<div id="myDIV">
cbcvbcvb
</div>
</div>
<script>
//org_html = document.getElementById("section1").innerHTML;
//new_html = "<div class='mydiv-container'>" + org_html + "</div>";
//document.getElementById("section1").innerHTML = new_html;
const parentObject = document.getElementById('section1').innerHTML;
[...parentObject].forEach((parent, i) => {
//const childElement = document.createElement('div');
const childElement = "<div class='slidesInner'>" + parentObject + </div>";
document.getElementById("section1").innerHTML = childElement;
});
</script>
结果应如下所示:
<div class="section" id="section1">
<div class="mydiv-container">
<div id="myDIV">
cbcvbcvb
</div>
</div>
</div>
<div class="section" id="section1">
<div class="mydiv-container"> <-- this is not showing in the second section
<div id="myDIV">
cbcvbcvb
</div>
</div>
</div>
答案 0 :(得分:2)
首先,这里有一个错字"<div class='slidesInner'>" + parentObject + </div>";
。您会看到关闭</div>"
时没有打开引号"
。
第二,您无需遍历innerHTML
的内容。因为innerHTML将提供类似<div id="myDIV">asdasd</div>
的内容。您可以使用querySelectorAll
并使用模板文字来创建新的包装div并设置innerHTML
const parentObject = document.querySelectorAll('.section');
parentObject.forEach(function(item, index) {
item.innerHTML = `<div class='slidesInner' id='subSection_${index}'>${item.innerHTML}</div>`;
})
.slidesInner {
color: green;
}
<div class="section" id="section1">
<div id="myDIV">
asdasd
</div>
</div>
<div class="section" id="section2">
<div id="myDIV2">
cbcvbcvb
</div>
</div>