Home

SiteMap

JavaScript - How to set DIV empty

← PrevNext →

There are two simple methods that you can use to empty or clear a DIV element in JavaScript. The first method is by setting the "innerHTML" property to an empty string. The second method is by using "replaceChildren()" method.

1st Method: Setting innerHTML Property as empty

Here's a <div> element with some content.

<div id='v1'>
    Hello, I am Arun Banik
</div>

Now, let's empty the DIV using innerHTML property.

<script>
    document.getElementById('v1').innerHTML = '';
</script>
Try it

I have explained about innerHTML in detail here...

2nd Method: Using replaceChildren() Method

Now, this method is interesting. The replaceChildren() method is used to replace the content of an element. It takes an argument or parameter. However, when you use this method without passing any parameter or argument, it replaces the content with an "empty string". For example,

<div id='v1'>
    Hello, I am Arun Banik
</div>
<script>
    document.getElementById('v1').replaceChildren();
</script>
Try it

The replaceChildre() method replaces the previous content with nothing or an empty string. So, you get an empty DIV element here.

You can do this using jQuery. Check this out.

Happy coding. 🙂

← PreviousNext →