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

114
Views
Crear un elemento y la capacidad de eliminarlo con JavaScript

Uso el comando insertAdjacentHTML en el evento de clic de un botón para agregar una etiqueta div a una parte de la página. Ahora, ¿cómo puedo ordenar que se elimine este div cuando se hace clic en el resto de la página en el body (excepto este div )?

De cualquier forma que lo cree, ¡el div se crea y elimina rápidamente!

 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(); } });

archivo HTML:

 <body> ... <button type="button" id="button">Create!</button> ... </body>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Antes de llamar a contains , primero debe comprobar que el nodo existe. getElementById no devuelve una lista de nodos (por lo que no hay .length ). Devuelve el nodo o null .

En segundo lugar, cuando tenga otro botón que debe crear el elemento, debe tener cuidado de que este clic no se considere como un evento "fuera" del nuevo elemento que debe eliminarlo nuevamente. Entonces cancele la propagación del clic del botón, para que no llegue al otro oyente.

Así que hazlo:

 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!