Home > OS >  How Do I Remove/Close A Div With JS?
How Do I Remove/Close A Div With JS?

Time:12-19

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>```

CodePudding user response:

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

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

use :

close.addEventListener("click", () => { alertbox.remove();})

CodePudding user response:

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).

  • Related