Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

appendChild Not Working

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?

like image 399
bingjie2680 Avatar asked Dec 06 '11 22:12

bingjie2680


3 Answers

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.

like image 103
kapa Avatar answered Sep 19 '22 22:09

kapa


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 
    }
}
like image 30
Edgar Avatar answered Sep 22 '22 22:09

Edgar


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().
like image 41
David Thomas Avatar answered Sep 18 '22 22:09

David Thomas