I’m trying to dynamically make an unordered list using javascript, where I just have to list the number of items that I want and it will display it in the list.
example input prompt “how many list items would you like?” if we input 2 and enter it should return
<ul> <li>hi</li> <li>hi</li> </ul>
I’ve simplified the HTML and javascript but i tried wrap the append and create variables in a for loop and nothing happened. heres the code html :
const numberofitemsel = document.getElementById('num-of-navitems'); const numberofitems = parseInt(numberofitemsel.value); const body = document.body; const savebtn = document.getElementById('save'); savebtn.addEventListener('click',()=>{ let ul =document.createElement("ul"); // append to body body.append(ul); // create list items for(var i=0;i<=numberofitems;i++){ let li=document.createElement("li"); li.innerText="hi"; // append to ul ul.appendChild(li); } });
<main> <h4>how many list items do you want?</h4> <input type="number" id="num-of-navitems"> <button type="button" id="save">save</button> </main>
so the output I want is the if I input 3 into my input box I want three list items:
<ul> <li>hi</li> <li>hi</li> <li>hi</li> </ul>
Advertisement
Answer
You should use for
loop in the savebtn.eventListener
:
for(let i=0;i<Math.floor(Number(numberofitemsel.value));i++) { let li = document.createElement("li"); li.innerText = "hi"; // append to ul ul.appendChild(li); }
The other parts of your code are OK.