Javascript 想要设置ul的liinnerHTML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6146607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Want to set li innerHTML of ul
提问by rach
I'm writing a javascript function where I get a ul
object from my HTML and want to set the text of one of the li elements in the
ul`. I'm doing:
我正在编写一个 javascript 函数,我ul
从我的 HTML 中获取一个对象,并希望设置其中一个li elements in the
ul`的文本。我正在做:
list = document.getElementById('list_name');
Then I want to access the ith li
element of list using a loop.
I have:
然后我想li
使用循环访问列表的第 i 个元素。我有:
for (i = 0; i < 5; i++) {
list[i].innerHTML = "<a>text</a>";
}
but this is not working. What is the proper way to do it?
但这不起作用。什么是正确的方法呢?
回答by alex
You need to access the child li
elements of the ul
. JavaScript and the DOM API can't automagically do that for you.
您需要访问子li
的元素ul
。JavaScript 和 DOM API 不能自动为你做这件事。
var list = document.getElementById('list_name'),
items = list.childNodes;
for (var i = 0, length = childNodes.length; i < length; i++)
{
if (items[i].nodeType != 1) {
continue;
}
items[i].innerHTML = "<a>text</a>";
}
You couldalso use getElementsByTagName('li')
but it will get alldescendent li
elements, and it seems you want only the direct descendants.
您也可以使用getElementsByTagName('li')
但它会获得所有后代li
元素,而且您似乎只想要直接后代。
You could also avoid innerHTML
if you want.
innerHTML
如果你愿意,你也可以避免。
var a = document.createElement('a'),
text = document.createTextNode('text');
a.appendChild(text);
items[i].appendChild(a);
innerHTML
can cause issues, such as lost event handlers and the performance issue of serialising and re-parsing the HTML structure. This should be negligible in your example, however.
innerHTML
可能会导致问题,例如丢失事件处理程序以及序列化和重新解析 HTML 结构的性能问题。但是,在您的示例中,这应该可以忽略不计。
回答by Glenn Ferrie
jQuery Sample code, although the others work:
jQuery 示例代码,尽管其他代码有效:
$("#list_name li").text("<a href=''>text</a>");
Its much more succinct with jQuery
jQuery 更简洁
回答by ZeroDarkThirty
You can try the following
您可以尝试以下操作
var el = document.createElement("li"),
content = document.createTextNode("My sample text"),
myUl = document.getElementById("ulOne");
el.appendChild(content);
el.id = "bar";
myUl.appendChild(el);
Here's the demo: http://jsfiddle.net/x32j00h5/
这是演示:http: //jsfiddle.net/x32j00h5/
回答by Necrower
I prefer a aproach using getElemenetByTagName, if somehow you get a extra node like a script tag or a span you will have problems. A guess this code will help you:
我更喜欢使用 getElemenetByTagName 的方法,如果你以某种方式获得了一个额外的节点,比如脚本标签或跨度,你就会遇到问题。猜测此代码将帮助您:
var list = document.getElementById("mylist");
var items = list.getElementsByTagName("li");
for(var i = 0, size = items.length; i< size; i++){
items[i].innerHTML = "<a href='#'>LINK</a>";
}