mercredi 9 juin 2021

Javascript : Element.replaceWith(node) not working as expected

I am trying to create a todoList app with vanilla js. So far i have finished markup, design and as well as added other functionalities such as adding submitted task to ui, deleting task, marking the task as completed.

Now i am stuck at adding the edit functionality.(And of course there are still other things to do like validation , implementing localStorage, adding reminder, making it responsive etc..)

The code which causes the problem starts at line 34 else if(targetClassName.contains('edit') and ends at 55

The error occurs at line 40

Here is my code => https://jsfiddle.net/Pixie_Dust/vg2twd35/36/

quick note : I worte some comments in the code which might help to understand my problem

Here is the problematic code and the error : Uncaught TypeError: Cannot read property 'previousElementSibling' of null at Function.taskEvents

even though it says that the error is in previousElementSibling as null i believe that it is caused by the replaceWith() 'because it worked before adding it'.

else if(targetClassName.contains('edit')) {
    const saveBtn = document.createElement('a');
    saveBtn.className = "btn";
    saveBtn.id = "saveBtn";
    saveBtn.innerHTML = '<i class="fas fa-save save"></i>';

    eventTarget.parentElement.replaceWith(saveBtn);
    //replace edit button with save button 
    console.log(eventTarget.parentElement);
    /* 
    Expected output : <a href="#" class="btn" id="saveBtn"><i class="fas fa-save save"></i></a>
    output shown : <a href="#" class="btn" id="editBtn"><i class="fas fa-save edit"></i></a>
    As you can see it got changed in the UI, but not in the elements
    */

    const taskContent = eventTarget.parentElement.parentElement.previousElementSibling;
    // Expected to get <td>Task content...</td>
    // shown output : null , i think that line 40 ```element.replaceWith()``` affected it's parent, it doesn't have a prent now, hence the below code/s doesn't work
    taskContent.setAttribute("contenteditable", "true");

    if (targetClassName.contains('save')) {
        editBtn.replaceWith(editBtn);
        taskContent.removeAttribute('contenteditable');
    }

Things i want to achieve :

  1. on clicking the edit icon, it should change to a save icon until the user clicks it so save the changes.

  2. add new attribute contenteditable=true on clicking the edit button,and after editing the text, the save icon should save the edited text and change contenteditable=false or remove it.

Aucun commentaire:

Enregistrer un commentaire