Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
29
rated 0 times [  36] [ 7]  / answers: 1 / hits: 32456  / 13 Years ago, tue, december 6, 2011, 12:00:00

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?


More From » dom

 Answers
149

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.


[#88712] Monday, December 5, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
natalyah

Total Points: 371
Total Questions: 90
Total Answers: 105

Location: The Bahamas
Member since Wed, Apr 12, 2023
1 Year ago
natalyah questions
;