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

103
Vistas
RE-add DOM element in eventlistener callback after removing it
const addtasks = document.getElementById('task-add-btn').addEventListener('click', (event)=>{
    const inputTask = document.createElement('input');
    inputTask.type = 'text';
    inputTask.placeholder = 'Add Task Description';
    console.log(inputTask);
    document.querySelector('.display-result-div').appendChild(inputTask);
    inputTask.addEventListener('change', (event)=>{
        fetch(`${window.origin}/add_task`, {
            method : "POST",
            credentials : 'include',
            body : JSON.stringify(event.target.value),
            cache : 'no-cache',
            headers : new Headers({
                "content-type" : 'application/json'
            })
        });
    });
    inputTask.remove();
    });

In above code I am creating an input tag on button-click and then removing that from DOM after getting its value. I want following to happen every time I click my button:

  1. Input tag is created and added to DOM, so that I can use its value
  2. At the end input tag is removed from DOM

Above code doesn't add input tag to DOM after it gets removed first time.

Any help will be appreciated. Thanks!

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Currently you're removing the inputTask element before it has a chance to be changed.

Before removing it though I would check to see if your fetch request returns a successful response, and also catch any errors:

const addtasks = document.getElementById('task-add-btn').addEventListener('click', (event) => {
  const inputTask = document.createElement('input');
  inputTask.type = 'text';
  inputTask.placeholder = 'Add Task Description';
  
  document.querySelector('.display-result-div').appendChild(inputTask);
  
  inputTask.addEventListener('change', (event) => {
    fetch(`${window.origin}/add_task`, {
      method: "POST",
      credentials: 'include',
      body: JSON.stringify(event.target.value),
      cache: 'no-cache',
      headers: new Headers({
        "content-type": 'application/json'
      })
    })
    .then(response => response.json())
    .then(data => {
      console.log('Success:', data);
      inputTask.remove();
    })
    .catch((error) => {
      console.error('Error:', error);
      inputTask.remove();
      // you may wish to keep the input field here in this case
    });
  });
  
});
<div class="display-result-div"></div>
<button id="task-add-btn">add</button>

about 4 years ago · Juan Pablo Isaza Denunciar

0

The added input is getting removed on #task-add-btn click itself. Ideally you would want to remove it once after the user entering some text and getting success response from backend.

So, moving the inputTask.remove() inside the success handler of fetch API would give you the expected behaviour.

const addtasks = document.getElementById('task-add-btn').addEventListener('click', (event) => {
  const inputTask = document.createElement('input');
  inputTask.type = 'text';
  inputTask.placeholder = 'Add Task Description';
  console.log(inputTask);
  document.querySelector('.display-result-div').appendChild(inputTask);
  inputTask.addEventListener('change', (event) => {
    console.log("change!!!");
    // Simulating the success response using `setTimeout` and removing the 
    // added input element after 1000ms
    setTimeout(() => {
      inputTask.remove();
    }, 1000);

   /* 
    // Ideally you would want to remove the newly added element once after getting the 
    // success response from the backend i.e., inside `.then` of the `fetch` API.
    fetch(`${window.origin}/add_task`, {
      method: "POST",
      credentials: 'include',
      body: JSON.stringify(event.target.value),
      cache: 'no-cache',
      headers: new Headers({
        "content-type": 'application/json'
      })
    }).then(res => {
      //Remove the element after success response
      inputTask.remove();
    }).catch(err => {
      //Error handling
    })
   */
  });
});
<div class="display-result-div"></div>

<button id="task-add-btn">Add Task</button>

For simplicity, here I have used setTimeout in order to remove the element after 1000ms after the user entering some text in the newly added input element.

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