fairly new to html, css, and javascript- also compeltely new to stackoverflow.
I am making an html list, which users can add to by typing in an text input, but I want to add buttons to each new li that will cause that specific li to change to a strikethrough text-decoration.
My javascript code for the function is:
function addListItem() {
var input = document.getElementById('listAdd').value;
var ul = document.getElementById("list");
var li = document.createElement("li");
var buttonId = document.getElementById('button1').id;
var button = document.createElement('input');
button.type = "button";
button.name = "name";
button.value = "Done";
button.id = buttonId +"1";
li.appendChild(button);
li.appendChild(document.createTextNode(" "+input));
ul.appendChild(li);
}
I'm assuming I need to create a separate function that would apply to each added item to the ul, but the issue I'm running into is the id of each new li.
As it currently stands, all new li will have an id of "button11", where as I would need them to each have a unique identifier.
Should I use an if statement to achieve this?
Thanks to any and all who have suggestions, citicism, etc.
button.id = buttonId +"1" is string concatenation, not any form of arithmetic or incrementation. You would need a number for both operands for arithmetic (and "1" is a string, not a number).
I agree with CertainPerformance that an id is likely unnecessary but if you did want a unique identifier for each button, you could use the count of existing buttons (as long as you are only adding and not removing buttons):
button.id = 'button' + li.getElementsByTagName("button").length + 1;
li.getElementsByTagName("button") will get an array of existing buttons under that <li>.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With