tobi1512
tobi1512

Reputation: 159

How to append <li> to a <ul> on button click

How to append <li> to a <ul> on a button click.

I have tried below script, but want to have a number appended to the end of <li>. Like item 0, item 1, item 2, etc..

var list = document.getElementById("list");
var add = document.getElementById('addElem');
add.addEventListener('click', function() {
  var itemsByTagName = document.getElementsByTagName("li");
  list.innerHTML += '<li>item</li>'
});
<ul id="list">
  <li>item
  </li>
</ul>
<button id="addElem">Add</button>

Upvotes: 2

Views: 3444

Answers (1)

Pugazh
Pugazh

Reputation: 9561

Here is a example to get started.

Note: For production use you might need to handle the variable i through server/session/local storage variable.

var i = 1;
var list = document.getElementById("list");
var add = document.getElementById('addElem');
add.addEventListener('click', function() {
  var itemsByTagName = document.getElementsByTagName("li");
  list.innerHTML += '<li>item ' + i++ + '</li>'
});
<ul id="list">
  <li>item
  </li>
</ul>
<button id="addElem">Add</button>

Upvotes: 2

Related Questions