Jordan Chapman
Jordan Chapman

Reputation: 13

How do i add an html list item to an already created list in javascript?

I have read other questions and articles on how to add a list item but none of these work. Here is my JavaScript:

var inpu = document.getElementById("inp").value;//get input text
var ul = document.getElementById("lis");//get list
var li = document.getElementById("li");//get list item
li.appendChild(document.createTextNode(inpu));
ul.appendChild(li);

This is what i read that i was supposed to do but they never showed me html so i can see how to do that part, which is why i am assuming that the problem is in my html. This is what my html looks like:

<body>
<input id="inp"/>
<button id="button">Submit</button>
<ul id="lis">
    <li id="li"> </li>
</ul>



<script src="This.js"></script>

Any help is greatly appreciated.

Upvotes: 1

Views: 203

Answers (2)

MrMadsen
MrMadsen

Reputation: 3012

'inpu' is equal to the value in the input field. When you first load that page there is no value in the input field so nothing is getting appended to the list item.

If you put the code into a function and then call that function when you click the button it will work. like this:

html:

<body>
<input id="inp"/>
<button id="button" onclick="putInList()">Submit</button>
<ul id="lis">
    <li id="li"> </li>
</ul>

javascript:

var putInList = function() {
    var inpu = document.getElementById("inp").value;//get input text
    var ul = document.getElementById("lis");//get list
    var li = document.getElementById("li");//get list item
    li.appendChild(document.createTextNode(inpu));
    ul.appendChild(li);
}

Upvotes: 0

Barmar
Barmar

Reputation: 780663

If you want to add a new list item, you need to use document.createElement('li'). Your code just replaces the contents of the existing li; the appendChild doesn't do anything, because it's already the last child.

document.getElementById("button").addEventListener("click", function() {
  var inpu = document.getElementById("inp").value; //get input text
  var ul = document.getElementById("lis"); //get list
  var li = document.createElement("li"); //get new list item
  li.appendChild(document.createTextNode(inpu));
  ul.appendChild(li);
});
<input id="inp" />
<button id="button">Submit</button>
<ul id="lis">
  <li id="li"></li>
</ul>

Upvotes: 1

Related Questions