xhallix
xhallix

Reputation: 3011

get ul in javascript and append li

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

Upvotes: 0

Views: 8739

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191729

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

ulnew[0].appendChild(newLi);

http://jsfiddle.net/eKeFN/

Upvotes: 8

Related Questions