Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

111
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda