Reputation: 1
So I have this following code set up to create an li
element when someone inputs something into a box. I also want the li
element to contain a unique ID which will begin with list-Item0
and go to list-Item1
, etc with every li
created when someone types into the box and adds the item.
Any idea how I would go about doing this? I don't know what JQuery is as I am a complete beginner so am looking for something extremely basic which I can implement in this code.
Here's what I have so far:
function addItemFunction() {
document.getElementById("itemList").innerHTML=document.getElementById("itemList").innerHTML + '<li>' + addNewBox.value + '</li>';
}
Upvotes: 0
Views: 5466
Reputation: 147363
As an extension to Phil's answer, you can avoid the global counter by keeping it in a closure:
var addItemFunction = function () {
var listItemCounter = 0;
return function () {
var li = document.createElement('li');
li.id = 'list-Item' + listItemCounter++;
li.innerHTML = addNewBox.value;
document.getElementById('itemList').appendChild(li);
};
}());
Upvotes: 2
Reputation: 164744
Simply keep a counter for the ID outside your function, create an <li>
element, set the ID and content, increment the counter and append the element to your itemList
.
var listItemCounter = 0;
function addItemFunction() {
var li = document.createElement('li');
li.id = 'list-Item' + listItemCounter++;
li.innerHTML = addNewBox.value;
document.getElementById('itemList').appendChild(li);
}
Upvotes: 6