appendChild不工作 [英] appendChild Not Working
问题描述
HTML:
<ul id="datalist">
</ul>
JavaScript:
JavaScript:
function add(content){
ul=document.getElementsByTagName("ul");
var li=document.createElement("li");
li.innerHTML=content;
ul.appendChild(li);
}
当我打电话添加
,未捕获TypeError:对象#< NodeList>没有方法'appendChild'
被抛出。任何想法为什么?
When I call add
, Uncaught TypeError: Object #<NodeList> has no method 'appendChild'
is thrown. Any idea why?
推荐答案
getElementsByTagName()
不返回一个元素,它返回一个 NodeList ,它是一个类似数组的对象。它基本上意味着你可以使用它作为一个数组。
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.
所以你可以这样做:
var ul = document.getElementsByTagName("ul")[0];
< org / en / DOM / document.getElementById> getElementById()
,如果该列表有ID? ID在整个文档中必须是唯一的,所以此方法只会返回一个元素。
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');
请注意请请确保将 ul
声明为您的函数的局部变量(添加 var
),除非您意图在外部使用它功能。
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.
这篇关于appendChild不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!