问题
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?
回答1:
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.
回答2:
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
// check the alignment on a number of cells in a table.
var table = document.getElementById("forecast-table");
var cells = table.getElementsByTagName("td");
for (var i = 0; i < cells.length; i++) {
var status = cells[i].getAttribute("data-status");
if ( status == "open" ) {
// grab the data
}
}
回答3:
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 what appendChild()
expects to work on; therefore you need to identify which of the array of nodes you want to work with:
function add(content){
ul=document.getElementsByTagName("ul")[0]; // the [0] identifies the first element of the returned array
var li=document.createElement("li");
li.innerHTML=content;
ul.appendChild(li);
}
Remember that if there's only one ul
on the page, you could use getElementsByTagName("ul")[0]
or (and this might be preferable) add an id
attribute to that ul
and then select it with getElementById()
, which will, as expected, return just that one id
.
References:
- getElementsByTagName().
- getElementById().
来源:https://stackoverflow.com/questions/8407487/appendchild-not-working