-2

It's Working But When Clicked Close Icon It's Not Removing
I Don't Know How Do I Do It!!! Because I'm Doing Custom Alert Box And I'm Doing This
Creating div And Not Removed

I Want To Close/Remove The div Element And The div Is In The createElement(); Function
And I Tried W3Schools And Stack Overflow Questions
But Still Not Working
I Don't Know Why

Here's My Code:

<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <title>Custom Alert Box</title>
</head>
<body>
    <button onclick="alert('hello')">Try it</button>
    <script>
        alert = function(arguments) {
            var alertbox = document.createElement("div");
            var close = document.createElement("img");
            var text = document.createTextNode(arguments);
            alertbox.setAttribute("style", `
                border: 0.8px solid #002;
                border-radius: 4px;
                box-shadow: 0 2px 4px #454c4e;
                padding: 6px;
                height: 80px;
                `
            );
            close.setAttribute("style", `
                width: 18px;
                height: auto;
                float: right;
                `
            );
            close.setAttribute("src", "https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-close-512.png");
            close.setAttribute("alt", "close");
            close.setAttribute("onclick", alertbox.remove()); // The Close Icon That Removes/Closes The Div
            alertbox.appendChild(text);
            alertbox.appendChild(close)
            document.body.appendChild(alertbox);
        }
    </script>
</body>
</html>```
Rana
  • 2,500
  • 2
  • 7
  • 28
  • What do you mean by "close" ? Do you want to delete the entire element from the DOM or do you want to hide the div ? – ThomasG2201 Dec 19 '21 at 11:56
  • 1
    Does this answer your question? [Add "onclick" handler to a dynamically created element in pure javascript](https://stackoverflow.com/questions/40930189/add-onclick-handler-to-a-dynamically-created-element-in-pure-javascript) – Ivar Dec 19 '21 at 11:57

2 Answers2

0

you should add an eventListener instead of setattribute. instead of :

close.setAttribute("onclick", alertbox.remove());

use :

close.addEventListener("click", () => { alertbox.remove();})
hassan souiti
  • 89
  • 1
  • 3
-2

If I understand well your question, you wanna delete a div from the DOM.

  • get the reference to that element with document.querySelector()
  • get the parent element of the result with myelement.parentElement
  • delete the element with the method parent.removeChild()

An other solution would be to hide the element once it's been created (with display: none CSS property for instance).

ThomasG2201
  • 676
  • 6
  • 25