appendChild Not Working

bingjie2680 picture bingjie2680 · Dec 6, 2011 · Viewed 29.7k times · Source

HTML:

<ul id="datalist">
</ul>

JavaScript:

function add(content){
   ul=document.getElementsByTagName("ul");
   var li=document.createElement("li");
   li.innerHTML=content;
   ul.appendChild(li);
}

When I call add, Uncaught TypeError: Object #<NodeList> has no method 'appendChild' is thrown. Any idea why?

Answer

kapa picture kapa · Dec 6, 2011

getElementsByTagName() does not return one element, it returns a NodeList, which is an array-like object. It basically means you can use it as an array.

So you could do for example:

var ul = document.getElementsByTagName("ul")[0];

But why don't you simply use getElementById(), if that list has an ID anyways? IDs must be unique in the whole document, so this method will only return one element.

var ul = document.getElementById('datalist');

Note: Please be sure to declare ul as a local variable to your function (add var), unless you mean to use it outside the function.