简体   繁体   English

如何使用按钮“ onclick”功能从“ div”元素中删除内容?

[英]How to remove the content from a “div” element using a button “onclick” function?

I have a div element that contains a number of images. 我有一个div元素,其中包含许多图像。 When the user clicks a button, I want the contents of the div to be removed (not the div itself, I want to reuse the div to potentially add new content). 当用户单击一个按钮时,我希望删除div的内容(而不是div本身,我想重用div来潜在地添加新内容)。

In my HTML, the div and button are defined as: 在我的HTML中, divbutton定义为:

<body>
    ...
    <div class="MyDiv"></div>
    ...
    <button id="removeDiv" onclick="removeDivFunction()">remove Div Function</button>
    ...
</body>

How do I write a function that removes all elements from this div ? 我如何编写一个函数来删除该div中的所有元素?

You have to call removeChild : 您必须致电removeChild

function removeDivFunction() {
   MyDiv.parentNode.removeChild(MyDiv);
}
<div id="div1" style="height:100px;width:300px;border:1px solid black;background-color:yellow;">

This is some text in the div.
<p>This is a paragraph in the div.</p>
<p>This is another paragraph in the div.</p>

</div>
<br>

<button>Remove div element</button>


$(document).ready(function(){
    $("button").click(function(){
        $("#div1").remove();
    });
});
function removeDivFunction() {
    $(".MyDiv").remove();
}

David has already pointed you to an existing question/solution. David已经为您指出了现有的问题/解决方案。
For reference consider reading: http://www.w3schools.com/js/js_htmldom_nodes.asp 供参考,请阅读: http : //www.w3schools.com/js/js_htmldom_nodes.asp
Its always a good idea to assign id to the div. 将id分配给div总是一个好主意。

Also if you are using jQuery you can delete element by $("#divid").remove() for reference see: https://api.jquery.com/remove/ 另外,如果您使用的是jQuery,则可以通过$(“#divid”)。remove()删除元素以供参考,请参见: https ://api.jquery.com/remove/

I hope this helps. 我希望这有帮助。

<div class="MyDiv">I need to remove</div>
<button id="removeDiv" onclick="removeDivFunction()">remove Div Function</button>  
function removeDivFunction() {
    var element = document.getElementsByClassName("MyDiv")[0];
    element.parentNode.removeChild(element);
}  

DEMO DEMO

You can try Html 您可以尝试HTML

<div id="some">Example</div>
<button onclick="myFunction()">Click me</button>

javascript JavaScript的

function myFunction() {
    var child = document.getElementById("some");
    child.parentNode.removeChild(child);
}

And if you want to erase content of DIV then use 如果要删除DIV的内容,请使用

  child.innerHTML = "";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM