JavaScript - Remove Element on Click

JavaScript - Remove Element on Click

Here is a JavaScript program example to remove an element on click.

JavaScript Remove Element on Click Example

In the following example, it will create five paragraphs, and when the user clicks on any paragraph, the JavaScript program will remove that element.

The Script for the HTML Head Part:

<style>
    p 
    {
        padding: 20px;
        margin: 10px 0;
        width: 400px;
        background-color: #eeeeff;
    }
</style>
<script>
    window.onload=function() {
        var paras = document.getElementsByTagName("p");
        for (var i = 0; i < paras.length; i++)
            paras[i].onclick=pruneparagraph;
    }
    function pruneparagraph() {
        var parent = this.parentNode;
        parent.removeChild(this);
        alert("paras " + document.getElementsByTagName("p").length);
    }
</script>

The Script for the HTML Body Part:

<p>
    This is paragraph one
</p>
<p>
    This is paragraph two
</p>
<p>
    This is paragraph three
</p>
<p>
    This is paragraph four
</p>
<p>
    This is paragraph five
</p>

Output

As shown in the featured image of this article.