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?
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:
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.Note: Please be sure to declare
ulas a local variable to your function (addvar), unless you mean to use it outside the function.