Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

112
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda