【appendChild】
appendChild 方法是添加节点,将节点添加到指定父节点内子节点列表的末尾。如果获取的节点是当前文档中现有节点的引用,那 appendChild 则将其从当前位置移动到新的位置。
<div id=\\\"main\\\"></div>
<script>
let createDiv = document.createElement(\\\'div\\\');
let createText = document.createTextNode(\\\'这是新添加的 div\\\');
createDiv.appendChild(createText);
let main = document.getElementById(\\\'main\\\');
main.appendChild(createDiv);
</script>
<div id=\\\"main\\\"><div>这是添加的 div</div></div>
<div id=\\\"outsideDiv\\\">这是添加的外层 div</div>
<div id=\\\"main\\\">
<p>main内容</p>
</div>
<script>
let outsideDiv = document.getElementById(\\\'outsideDiv\\\');
let main = document.getElementById(\\\'main\\\');
main.appendChild(outsideDiv);
</script>
<div id=\\\"main\\\">
<p>main内容</p>
<div id=\\\"outsideDiv\\\">这是添加的外层 div</div>
</div>
<div id=\\\"main\\\">
<div id=\\\"main-container\\\">container</div>
</div>
<script>
let mainDiv = document.getElementById(\\\'main\\\');
let mainDivContainer = document.getElementById(\\\'main-container\\\');
mainDiv.removeChild(mainDivContainer);
</script>
<div id=\\\"main\\\">main</div>
<script>
let mainDiv = document.getElementById(\\\'main\\\');
if( mainDiv.parentNode ){
mainDiv.parentNode.removeChild(mainDiv);
}
</script>
参考文档:
https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild
原创文章,作者:小道研究,如若转载,请注明出处:https://www.sudun.com/ask/34561.html