How do you remove and hide HTML elements in plain Javascript?

假如想象 提交于 2019-12-10 19:59:47

问题


I have this HTML:

<body>
    <div id="content-container" style="display:none">
         <div>John</div>
    </div>
    <div id="verifying">
         <div id="message">Verified</div>
    </div>
</body>

And this Javascript:

var body = document.body;
var signup = document.getElementById("content-container");

setTimeout(function(){
    body.removeChild('verifying');
    signup.style.display = "block";
}, 5000);

I am trying to remove <div id="verifying"> and show <div id="content-container"> after 5 seconds, but for some reason it is not working. Any idea why? I am loading the script after the page loads so that is not the problem.


回答1:


You need to pass an element reference to removeChild, not a string:

body.removeChild(document.getElementById('verifying'));

You could also just hide it:

document.getElementById('verifying').style.display = "none";



回答2:


your removeChild needs to get an element, not a string

var body = document.body;
var signup = document.getElementById("content-container");

setTimeout(function(){
    body.removeChild(document.getElementById('verifying'));
    signup.style.display = "block";
}, 5000);



回答3:


to remove you can use (as stated) removeChild:

var x = document.getElementById('elementid');
x.parentNode.removeChild(x);

And to hide an element:

var x = document.getElementById('elementid');
x.style.display="none";

EDIT:

oh and if you want it hidden but not taken "out of flow", use this:

var x = document.getElementById('elementid');
x.style.visibility="hidden";


来源:https://stackoverflow.com/questions/7458619/how-do-you-remove-and-hide-html-elements-in-plain-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!