0

I need loop in Javascript - when You click on button it add ol tu ul and gave id with number, like this:

<ol id="single-task1"></ol>
<ol id="single-task2></ol>

And so on...

When I tried whit loop like this:

taskNumber = 0;

        for (var i; i<999; i++){
            taskNumber++;
        }

        var ol = document.createElement('ol'); //creating element ol
        taskValue = textField.value; //getting value from user
        taskList.appendChild(ol); //add ol to ul
        ol.id = 'single-task-'+taskNumber;
        ol.innerHTML = taskValue; //add value from user to new ol

All ol elements still have "single-task-0"... Probably loop is in wrong place or loop is wrong.

3
  • Do all the creation in the loop instead of after the loop is complete Commented Nov 7, 2017 at 18:32
  • You only incrementing taskNumber within the loop. Then, you are only working on one ol-element. Try using a debugger within your browser to see what your code is doing. Commented Nov 7, 2017 at 18:32
  • Why are you putting <ol> elements inside a <ul>? Did you mean <li>? Do you really need one thousand IDs? Why not simply taskList.children[taskNumber]? Commented Nov 7, 2017 at 18:35

1 Answer 1

1

You are confusing your taskNumber and your i variable. Initialize i = 0 in your loop and use that. Do all of your work within the loop. You don't need taskNumber.

Sign up to request clarification or add additional context in comments.

Comments

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.