Javascript 用javascript替换div内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7173691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:11:05  来源:igfitidea点击:

replacing div content with javascript

javascript

提问by sameold

I'm trying to do this with pure javascript, not with jquery. I have a div that has an id testand contains other divs inside it. How do I empty the content of this div and replace it with other html?

我正在尝试使用纯 javascript 而不是 jquery 来做到这一点。我有一个 div,它有一个 idtest并在其中包含其他 div。如何清空此 div 的内容并将其替换为其他 html?

<div id="test">
   <div>...</div>
   <div>...</div>
   <div>...</div>
</div>

回答by Ian R.B.

document.getElementById("test").innerHTML = "new content"

回答by Shlomi Komemi

clear the div:

清除div:

document.getElementById('test').innerHTML = '';

replace it :

代替它 :

var h1 = document.createElement('h1');
h1.innerHTML = "hello world!";
document.getElementById('test').appendChild(h1);

回答by Adrian Heine

Use document.getElementById('test').innerHTML = ''.

使用document.getElementById('test').innerHTML = ''.

回答by shanethehat

document.getElementById("test").innerHTML = "Some other Content";

回答by Patelify

var testDiv = document.getElementById("test");
testDiv.innerHTML = "<h5>It works!</h5>";

回答by Chris Pont

Off the top of my head, I think this should work....

在我的头顶上,我认为这应该有效......

document.getElementById("test").innerHTML = "";