Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add list elements dynamically to ul element

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>
like image 810
Daniele Cordano Avatar asked Oct 19 '22 10:10

Daniele Cordano


2 Answers

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

like image 50
Andraz Avatar answered Oct 29 '22 18:10

Andraz


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>
like image 26
dimlucas Avatar answered Oct 29 '22 17:10

dimlucas