Home > other >  create a Edit Button while manipulating DOM in javascript
create a Edit Button while manipulating DOM in javascript

Time:12-13

I am creating a simple TODO APP, which adds and deletes and edits a task when it's added, I am trying to figure out how to do edit a task. should I create a new P tag and equal it to par.value?

h1.innerText = 'TODO LIST';
document.body.appendChild(h1);

const input = document.createElement('input');
document.body.appendChild(input);

const addBtn = document.createElement('button');
addBtn.innerText = 'Add';
document.body.appendChild(addBtn);

const container = document.createElement('div');
container.innerText = 'Output';
document.body.appendChild(container);



addBtn.addEventListener('click', function(){

  const par = document.createElement('p');
  par.innerText = input.value;
  container.appendChild(par);

  const deleteBtn =document.createElement('button');
  deleteBtn.innerText = 'Delete';
  par.appendChild(deleteBtn);

  const editBtn = document.createElement('button');
  editBtn.innerText = 'Edit';
  par.appendChild(editBtn);

  deleteBtn.addEventListener('click', function(){

    this.parentElement.remove();

    editBtn.addEventListener('click', function(){      

    })
  })
})



CodePudding user response:

There are many ways how you can do this. One way is to use the attribute contenteditable for your paragraph. See this example:

const h1 = document.createElement('h1');
h1.innerText = 'TODO LIST';
document.body.appendChild(h1);

const input = document.createElement('input');
document.body.appendChild(input);

const addBtn = document.createElement('button');
addBtn.innerText = 'Add';
document.body.appendChild(addBtn);

const container = document.createElement('div');
container.innerText = 'Output';
document.body.appendChild(container);



addBtn.addEventListener('click', function() {

  const par = document.createElement('p');
  par.innerText = input.value;
  container.appendChild(par);

  const deleteBtn = document.createElement('button');
  deleteBtn.innerText = 'Delete';
  container.appendChild(deleteBtn);

  const editBtn = document.createElement('button');
  editBtn.classList.add('edit');
  editBtn.innerText = 'Edit';
  container.appendChild(editBtn);

  deleteBtn.addEventListener('click', function() {

    this.parentElement.remove();

    editBtn.addEventListener('click', function() {

    })
  })
})

// Since the selector ".edit" is dynamic, listen to all elements
document.querySelector('*').addEventListener('click', (e) => {
  // Return, if the element has not the class "edit"
  if (e.target.className !== 'edit') return 
  // Set attribute to the paragraph
  e.target.previousSibling.previousSibling.setAttribute('contenteditable', 'true'); 
  // focus the paragraph
  e.target.previousSibling.previousSibling.focus(); 
});

  • Related