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

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

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 Relatório

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 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