附加子不工作
HTML:
<ul id="datalist">
</ul>
JavaScript:
function add(content){
ul=document.getElementsByTagName("ul");
var li=document.createElement("li");
li.innerHTML=content;
ul.appendChild(li);
}
当我调用 add
时,Uncaught TypeError: Object #
。知道为什么吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
getElementsByTagName()
不返回一个元素,它返回一个 NodeList,这是一个类似数组的对象。这基本上意味着您可以将其用作数组。所以你可以这样做:
但是为什么不简单地使用
getElementById()
< /a>,如果该列表有 ID 的话? ID 在整个文档中必须是唯一的,因此该方法只会返回一个元素。注意:请务必将
ul
声明为函数的局部变量(添加var
),除非您打算在函数外部使用它。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
ul
as a local variable to your function (addvar
), unless you mean to use it outside the function.document.getElementsByTagName 不返回元素,而是返回元素数组。
您需要循环该数组或获取一些唯一的元素。
查看此文档: https://developer.mozilla.org/en/DOM/element.getElementsByTagName
document.getElementsByTagName doesn't return a Element, but returns an Array of Elements.
You need to loop this array or get some unique Element.
Look this documentation: https://developer.mozilla.org/en/DOM/element.getElementsByTagName
您遇到的问题是
getElementsByTagName()
(请注意函数名称中的“s”隐含的复数)返回 DOM 节点的数组,而不是单个DOM 节点,这是appendChild()
期望处理的内容;因此,您需要确定要使用哪个节点数组:请记住,如果页面上只有一个
ul
,则可以使用getElementsByTagName( "ul")[0]
或(这可能更好)向该ul
添加一个id
属性,然后选择使用getElementById()
,正如预期的那样,它只会返回那个 id。参考文献:
getElementsByTagName()
。getElementById()
。The problem you have is that
getElementsByTagName()
(note the plural implied by the 's' in the name of the function) returns an array of DOM nodes, not a single DOM node, which is whatappendChild()
expects to work on; therefore you need to identify which of the array of nodes you want to work with:Remember that if there's only one
ul
on the page, you could usegetElementsByTagName("ul")[0]
or (and this might be preferable) add anid
attribute to thatul
and then select it withgetElementById()
, which will, as expected, return just that oneid
.References:
getElementsByTagName()
.getElementById()
.