简体   繁体   中英

DOM Manipulation

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

}

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

JSFiddle demo .


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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM