javascript中是否有任何方法/方法动态添加子节点列表元素? [英] Is there any method/way in javascript to add a child node to list element dynamically?
问题描述
如果我有一个无序列表,如
If I have an unordered list like
<ul id="list">
<li>Helo World-1</li>
<li>Helo World-2</li>
<li>Helo World-3</li>
</ul>
我想动态添加一个子列表项。有没有任何方法在javascript中做到这一点。我该怎么做
编辑
我需要一个下一个级别的项目,即我在OP中提到的Helo World的子列表,如下所示。这里还有一个问题是我需要这些项目作为我的代码的永久性部分。
I want to add a sublist item to it dynamically. Is there any method in javascript to do that. How could I do it. edit I need an item at next level, i.e. a sub list of Helo World that I mentioned in OP too, something like as under. One more issue here is that I need the items to be a permanent part of my code.
<ul id="list">
<li>Helo World-1</li>
<li>Helo World-2</li>
<li>Helo World-3</li>
<ul>
<li>One</li>
<li>Two</li>
</ul>
</ul>
推荐答案
使用纯DOM方法:
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode("Your list item text"));
将列表项添加到列表的末尾:
To add the list item to the end of the list:
ul.appendChild(li);
在现有列表项之间插入列表项(注意,您必须提供现有列表项这个例子中的id):
To insert the list item between existing list items (note you'd have to give the existing list item an id in this example):
ul.insertBefore(li, document.getElementById("list_item_id"));
更新
如果要添加一个嵌套列表,您需要将其添加到列表项,而不是直接列在列表中才能生效:
Update
If you want to add a nested list, you'll need to add it to a list item rather than directly inside the list in order for it to be valid:
var lis = ul.getElementsByTagName("li");
var lastLi = lis[lis.length - 1];
var nestedUl = document.createElement("ul");
var nestedLi = nestedUl.appendChild(document.createElement("li"));
nestedLi.appendChild(document.createTextNode("One"));
lastLi.appendChild(nestedUl);
这篇关于javascript中是否有任何方法/方法动态添加子节点列表元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!