0

What I'm trying to do is creating a <li> which should be added to the existing <ul> I want to append the textnode to the without giving it an ID. I try to do it with pure JavaScript, without jQuery.

What I got so far (and it does not work ):

function addElement () {
    var newLi = document.createElement("li");
    var text = document.createTextNode("Teststring in <li>");
    newLi.appendChild(text);
    var ulnew = document.getElementsByTagName('ul')
    ulnew.appendChild(newLi)    
}

HTML

<body onload="addElement()">
    <ul></ul>
</body>

Anyone who can help out? Thanks

Jaak Kütt
  • 2,566
  • 4
  • 31
  • 39
xhallix
  • 2,919
  • 5
  • 37
  • 55
  • possible duplicate of [How to access HTML element without ID?](http://stackoverflow.com/questions/236624/how-to-access-html-element-without-id) – Nir Alfasi Feb 25 '13 at 18:46

1 Answers1

8

getElementsByTagName returns a node list. You need to get a specific tag from that:

ulnew[0].appendChild(newLi);

http://jsfiddle.net/eKeFN/

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405