Javascript todo list edit function

43 views Asked by At

In the code below the function replaces the text content of all elements with the class "todos" with the value entered in the input field with the id "myinput". I want it to replace only that particular element

const target = document.getElementsByClassName("fa fa-edit");
const sumbitBtn = document.getElementById("submit");

var arrayform = Array.from(target) //creats an array of the target 
arrayform.forEach((e) => { // can access each of the edit icons sort of like for loop

e.addEventListener("click", function () {
    document.getElementById("myinput").focus()
    const myinput = document.getElementById("myinput");
    let currentValue = e.parentElement.previousElementSibling.textContent;
    let currentElement=e.parentElement.previousElementSibling
    myinput.value = currentValue;
     let inputtextValue= myinput.value
     sumbitBtn.addEventListener("click", function () {
        let replace=document.getElementsByClassName("todos");
        let replacearray = Array.from(replace)//creats an array of the replace
        replacearray.forEach((i) => {
             i.textContent = document.getElementById("myinput").value
    



     })
        
})

})

});
    

This code replaces all of the elements.

1

There are 1 answers

0
Syed Muhammad Ali Raza On
  • Move sumbitBtn decalration inside adlistner

  • Use insertAdjacentElement to add sumbitbtn after the current element

    const target = document.getElementsByClassName("fa fa-edit");

     var arrayform = Array.from(target);
    
     arrayform.forEach((e) => {
       e.addEventListener("click", function () {
         const myinput = document.getElementById("myinput");
         let currentValue = e.parentElement.previousElementSibling.textContent;
         let currentElement = e.parentElement.previousElementSibling;
         myinput.value = currentValue;
    
         let sumbitBtn = document.createElement("button");
         sumbitBtn.textContent = "Submit";
         sumbitBtn.addEventListener("click", function () {
           currentElement.textContent = myinput.value;
         });
    
         currentElement.insertAdjacentElement("afterend", sumbitBtn);
       });
     });