4.10. 替换元素为新内容

如果已经获取了一个元素,可以使用 replaceChild 函数来替换它的全部内容。

例 4.13. 替换图片为替代(alt)文本

假设页面上有一个元素 ID 为 "annoyingsmily"

var theImage, altText;
theImage = document.getElementById('annoyingsmily');
if (theImage) {
	altText = document.createTextNode(theImage.alt);
	theImage.parentNode.replaceChild(altText, theImage);
}
[注意]

如果要用一大段 HTML 替换一个元素,您可以构造 HTML 为一个字符串,然后设置元素的 innerHTML 属性

实例

← 删除元素
快速插入复杂的 HTML →