Remove all child elements of a parent by using JavaScript or JQuery

Here we explaining how to remove all HTML DOM child elements of a parent by using JavaScript or JQuery.

Eg:
<div id="Parent">
<span>This is some text in the div.</span>
<p>This is a paragraph in the div.</p>
<p>This is another paragraph in the div.</p>
<input type="text" value="webspeckle.com"/>
</div>
In the above example div is the parent element because 'div' tag is wrapped the other HTML DOM (Document Object Model) elements. Here the parent has four child elements. i.e span,p,input.

We can remove the elements by two way.

1) Remove the parent element and its child elements.
2) Remove only the child elements.

In JQuery it is very easy
Catch the parent element. Remove the parent element & its child or Delete all child elements.

$("#Parent").remove(); //Removes the selected element (and its child elements)
$("#Parent").empty(); //Removes the child elements from the selected element
In JavasCript
Remove all child elements
var Parent = document.getElementById("Parent");
while (Parent.hasChildNodes())
{
   Parent.removeChild(Parent.firstChild);
}
Remove parent and its child elements
var Parent = document.getElementById("Parent");
var ParentWrapper = Parent.parentNode;
while (ParentWrapper.hasChildNodes())
{
   ParentWrapper.removeChild(ParentWrapper.firstChild);
}

No comments:

Post a Comment