Is there a function like document.getElementById("FirstDiv").clear()
?
This question is related to
javascript
html
dom
var p=document.getElementById('childId').parentNode;
var c=document.getElementById('childId');
p.removeChild(c);
alert('Deleted');
p is parent node and c is child node
parentNode is a JavaScript variable which contains parent reference
Easy to understand
child.remove()
For your use case:
document.getElementById("FirstDiv").remove()
This is recommended by W3C since late 2015, and is vanilla JS. All major browsers support it.
Supported Browsers - 96% May 2020
Use the following code:
//for Internet Explorer
document.getElementById("FirstDiv").removeNode(true);
//for other browsers
var fDiv = document.getElementById("FirstDiv");
fDiv.removeChild(fDiv.childNodes[0]); //first check on which node your required node exists, if it is on [0] use this, otherwise use where it exists.
You should probably use a JavaScript library to do things like this.
For example, MochiKit has a function removeElement, and jQuery has remove.
You should be able to use the .RemoveNode method of the node or the .RemoveChild method of the parent node.
A jQuery solution
HTML
<select id="foo">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
Javascript
// remove child "option" element with a "value" attribute equal to "2"
$("#foo > option[value='2']").remove();
// remove all child "option" elements
$("#foo > option").remove();
References:
Attribute Equals Selector [name=value]
Selects elements that have the specified attribute with a value exactly equal to a certain value.
Child Selector (“parent > child”)
Selects all direct child elements specified by "child" of elements specified by "parent"
Similar to .empty(), the .remove() method takes elements out of the DOM. We use .remove() when we want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.
You have to remove any event handlers you've set on the node before you remove it, to avoid memory leaks in IE
If you want to clear the div and remove all child nodes, you could put:
var mydiv = document.getElementById('FirstDiv');
while(mydiv.firstChild) {
mydiv.removeChild(mydiv.firstChild);
}
Source: Stackoverflow.com