Home > Net >  Create an element and the ability to remove it with JavaScript
Create an element and the ability to remove it with JavaScript

Time:05-29

I use the insertAdjacentHTML command in click event of a button to add a div tag to a part of the page. Now how can I order this div to be remove when the rest of the page is clicked on the body (except for this div)?

Any way I create it, the div is created and removed quickly!

let newElement = '<div id="new-element">...</div>';
document.getElementById('button').addEventListener('click', function (event) {
    document.body.insertAdjacentHTML('beforeend', newElement);
}

document.addEventListener('click', function (event) {
if (!document.getElementById('new-elemnt'element').contains(event.target) && document.getElementById('new-elemnt'element').length !== 0)
    {
        document.getElementById('new-elemnt'element').remove();
    }
});

html file:

<body>
    ...
    <button type="button" id="button">Create!</button>
    ...
</body>

CodePudding user response:

Before calling contains you should first check that the node exists. getElementById does not return a node list (so there is no .length). It returns either the node or null.

Secondly, when you have another button that must create the element, you must take care that this click is not considered as an event "outside" the new element that must remove it again. So cancel the propagation of the button click, so that it doesn't reach the other listener.

So do:

const button = document.querySelector("button");

button.addEventListener("click", function(e) {
    e.stopPropagation();
    let node = document.getElementById('new-element');
    if (node) return; // It's already created
    let newElement = '<div id="new-element">new node</div>';
    document.body.insertAdjacentHTML('beforeend', newElement);
});

document.addEventListener('click', function (event) {
    let node = document.getElementById('new-element');
    if (node && !node.contains(event.target)) {
        node.remove();
    }
});
<div id="outside">outside</div>
<button>Add the DIV</button><br>

  • Related