0

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>';  
}
1
  • 1
    @DeanRather—no, don't do that. Much better for the OP to learn plain JS, then make his/her own decision about which library (if any) best suits their needs for a particular purpose. Commented Jul 14, 2015 at 0:33

2 Answers 2

6

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

I was just making a JS Fiddle for you to mess with when Phil posted this. Here ya go: jsfiddle.net/0fn8wf65
2

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);
    };
}());

1 Comment

The counter in my answer isn't necessarily global, it's just outside the function (as it is in this answer).

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.