Reputation: 6136
Newbie question - Is this code eloquent enough to create four list items? or Should I be using documentFragment instead? The code seems to work fine - JsFiddle.
Created list and li variables
var list = document.getElementById("myList");
var li = null;
Created x number of list elements and companion text nodes
for(var i=1; i<=4; i++){
var li = document.createElement("li");
li.appendChild(document.createTextNode("Number " + i));
Add li to list
list.appendChild(li);
}
Upvotes: 0
Views: 66
Reputation: 4656
Actually there is an error, because you're adding the li
s to the body
instead of the ul
also the markup is not well created, change
<ul class="myList"></ul>
with
<ul id="myList"></ul>
To use an id
and then:
var list = document.getElementById("myList");
var li = null;
for(var i=1; i<=4; i++){
var li = document.createElement("li");
li.appendChild(document.createTextNode("Number " + i));
//document.body.appendChild(li); **error here**
list.appendChild(li); //fix
}
Upvotes: 2
Reputation: 128791
Based entirely on the JSFiddle demo you've provided: No. What you currently have is semantically incorrect. You're currently appending your li
to the body
, not the ul
element:
<ul></ul>
<li>Number 1</li>
Change:
document.body.appendChild(li);
To:
list.appendChild(li);
As for the code you've provided in the question, you also need to change it so that your li
elements get appended to your ul
element. You also need to change your class
into an ID
, as getElementById("myList")
pulls an element with an ID of "myList", whereas your current ul
has no such ID.
Upvotes: 4