admin管理员组文章数量:1331849
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>
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>
Share
Improve this question
edited May 5, 2016 at 6:46
Madhawa Priyashantha
9,9007 gold badges38 silver badges64 bronze badges
asked May 5, 2016 at 6:42
Daniele CordanoDaniele Cordano
1031 silver badge7 bronze badges
2
-
Use
window.onload
instead ofdocument.onload
.. I am not sure whendocument.onload
will get invoked... – Rayon Commented May 5, 2016 at 6:46 - Fiddle here...jsfiddle/rayon_1990/o93ghfc9/3 – Rayon Commented May 5, 2016 at 6:46
2 Answers
Reset to default 3fixed fiddle here: https://jsfiddle/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
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>
本文标签: javascriptAdd list elements dynamically to ul elementStack Overflow
版权声明:本文标题:javascript - Add list elements dynamically to ul element - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742217008a2434754.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论