这里我有一个示例,使用element.replaceChild() method.To替换无序列表的第一个子节点,替换前一个节点,使用documen.createTextNode().But创建textNode,问题是它的称为replaceChild方法,那么它应该替换为child.And,我要用textNode.But替换它,令人惊讶的是,被替换的孩子有一个子弹标记,infront it.As textNode不是一个列表项,那么为什么子弹标记不是removed.Though,问题不是严重的one.Posted,而是满足我的curiosity.thanks!
jsFIDDLE
<!DOCTYPE html>
<html>
<body>
<ul id="myList"><li>Coffee</li><li>Tea</li><li>Milk</li></ul>
<p id="demo">Click the button to replace the first item in the the list</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var textnode=document.createTextNode("Water");
var item=document.getElementById("myList").childNodes[0];
item.replaceChild(textnode,item.childNodes[0]);
}
</script>
</body>
</html>发布于 2014-08-27 15:01:21
item引用第一个li元素。然后替换li元素(item.childNodes[0])的第一个子元素,即文本节点Coffee。
您永远不会替换li元素,只替换它的内容。
如果要替换li元素,请使用
var item=document.getElementById("myList");而不是。
https://stackoverflow.com/questions/25530520
复制相似问题