[英]How to replace an HTML element with another one?
例如,如何替换此页面代码:
<div class="parent">
<!-- possibly other elements -->
<div class="toselect">hello people</div>
<!-- possibly other elements -->
</div>
有了这个:
<div class="parent">
<!-- possibly other elements -->
<span class="new" style="color:red">hi guys</span>
<!-- possibly other elements -->
</div>
? 请注意,.parent 的孩子的数量,任何元素的完整代码都是未知的。 唯一已知的是选择要替换的元素所需的选择器('.toselect'),以及要添加的元素的代码。
尝试使用以下代码。
document.getElementById("change").addEventListener("click", function() { var oldEle = document.querySelector(".toselect"); var newEle = document.createElement("span"); newEle.innerHTML = "hi guys"; newEle.classList.add("new"); newEle.style.color = "red"; oldEle.parentNode.replaceChild(newEle, oldEle); });
<div class="parent"> <div>other element</div> <div class="toselect">hello people</div> <div>other element</div> </div> <br> <button id="change">Change Element</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.