6

I would like to add more li elements, like the first one, dynamically, i.e. by pressing a button. Here is a not working example on jsfiddle

document.onload = init;
function init(){
  document.getElementById('add').onclick = add;
}
function add(){
  var el = document.getElementById('list');
  var node = document.createElement("li");
  var link = document.createElement("link");
  link.setAttribute('href', 'www.google.it');
  link.setAttribute('name', 'link');
  node.appendChild(link);
  el.appendChild(node);
}
<ul id="list">
  <li>
    <a href="www.google.it">link</a>
  </li>
</ul>
<button id="add">Add link</button>
Madhawa Priyashantha
  • 9,633
  • 7
  • 33
  • 60
Daniele Cordano
  • 103
  • 1
  • 7

2 Answers2

3

fixed fiddle here: https://jsfiddle.net/overlord_tm/jj3j356y/6/

You probably want to create an a element, not link. Also, you want to set innerText property, instead of name attribute. And as Rayon mentioned, use window.onload

Andraz
  • 709
  • 2
  • 7
  • 16
1

window.onload = init;
function init(){
  document.getElementById('add').onclick = add;
}
function add(){
  var el = document.getElementById('list');
  var node = document.createElement("li");
  var link = document.createElement("a");
  link.setAttribute('href', 'www.google.it');
  link.innerHTML = "link";
  node.appendChild(link);
  el.appendChild(node);
}
<ul id="list">
  <li>
    <a href="www.google.it">link</a>
  </li>
</ul>
<button id="add">Add link</button>
dimlucas
  • 5,040
  • 7
  • 37
  • 54