user3432456
user3432456

Reputation: 1

How to make button that removes div where it is located?

I want to make button that removes div where button is located.

This current solution removes current div only temporary, BUT i want it completely be removed from this html file. Is that possible?

I am done so far:

<head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <link rel="stylesheet" media="screen" type="text/css" href="styles.css"/>
 <title>Orders</title>
 <center>
 <style>
  div 
  {width:797px;
  border:2px solid; 
  background-color:white;
  text-align:left;
  margin-bottom:2px;}
 </style>
<script type="text/javascript">
 function deleteline(buttonObj)
 {
 var node = buttonObj;
 do
 {
 node = node.parentNode;
 }
 while
 (node.nodeType != 1 && node.nodeName != 'div');
 node.parentNode.removeChild(node);
 }
</script>
</head>
<center><a href=panel.html>back</a></center>

<div>
<input type="button" onclick="deleteline(this)" value="Remove this DIV" />
</div>

Upvotes: 0

Views: 66

Answers (1)

Mehran Hatami
Mehran Hatami

Reputation: 12961

BUT i want it completely be removed from this html file.

The point is all you can do using JavaScript can actually creates client-side changes, so if you really want to delete the div element from your html file, the only thing you can do is creating a Server-side API and do a XHR request to that API, then remove it on the server side.

The other way to simulate this is to set an ID on that div element and save the last state of this element in the client using localStorage, after it got deleted, like:

function deleteline(buttonObj){
    var node = buttonObj;
     do {
         node = node.parentNode;
     }
     while (node.nodeType != 1 && node.nodeName != 'div');
     node.parentNode.removeChild(node);

     var deleted_divs = localStorage["deleted_divs"];
     var deletedDivs = deleted_divs ? JSON.parse(deleted_divs) ? [];
     deletedDivs.push(node.id);
     localStorage["deleted_divs"] = JSON.stringify(deletedDivs);
}

then check it whenever the DOM gets loaded:

document.addEventListener("DOMContentLoaded", function(event) {
    var deleted_divs = localStorage["deleted_divs"];
    if(deleted_divs){
        var deletedDivs = JSON.parse(deleted_divs),
            i = 0,
            l = deletedDivs.length;
        for( ; i < l ; i++){
            var el = document.getElementById(deletedDivs[i]);
            if( el ){
                el.parentNode.removeChild(el);
            }
        }
    }
});

Upvotes: 2

Related Questions