Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

110
Views
Create an element and the ability to remove it with JavaScript

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>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!