0

I'm trying to make my basic to do list better and I want to be able to delete a task when a button is clicked. How can I go about doing this? I've given the button dynamic ID's but cant seem to find out how to return that specific ID when a specific button is clicked.

Javascript

let Task = [];

function addTask(){
    //assign input to array
    var task = document.getElementById("userInput").value;
    Task.push(task);

    //creates node and shows where to find value
    let node = document.createElement("li");
    let textNode = document.createTextNode(
        document.getElementById("userInput").value
    );

    //create button for text node to delete
    const btn = document.createElement('button');
    btn.innerHTML = 'Delete';


    //adds task to webpage
    node.appendChild(textNode);
    document.getElementById("myList").appendChild(node);


    //Adds button to webpage, gives button dynamic ID
    document.getElementById("myList").appendChild(btn).id = Task.length;


}

1 Answer 1

1

If I understand correctly what you want is to assign a dynamic ID and return that ID by clicking the button, correct?

In this case you can try something like:

// Adds button to webpage, gives button dynamic ID
document.getElementById("myList").appendChild(btn);
btn.setAttribute("id", "myCustomId");

document.getElementById("myList").appendChild(btn);
btn.setAttribute("onclick", "alert('Current button ID: '+this.id)");
Sign up to request clarification or add additional context in comments.

3 Comments

Wheres a good place to find more information about javascript working with html?
Don't create custom attributes, use data-XXX attributes.
You can find tutorials about HTML + JS in Youtube (like in freeCodeCamp.org channel)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.