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

98
Views
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 answers
Answer question

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 Report

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