0
我想從div
(<div id='foo'>
)中刪除span
以下的元素,並追加新創建的節點,而不是每個節點。刪除並追加節點
我正在使用循環遍歷div
的所有子節點,並且找到的每個節點都使用removeChild
刪除它並附加一個新創建的節點。
我得到O/P爲
<div id='foo'>
<SPAN>new text</SPAN>
</div>
我想要的O/P如下
<div id='foo'>
<SPAN>new text</SPAN>
<SPAN>new text</SPAN>
<SPAN>new text</SPAN>
</div>
代碼問題如下提前
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
</HEAD>
<BODY>
<div id='foo'>
<SPAN>welcome to the world of translation.</SPAN>
<SPAN>Thank you for using it</SPAN>
<SPAN>visit again</SPAN>
</div>
<table border="0" cellspacing="5" cellpadding="0" class="lipi-header-logo-menu">
<tr>
<td align="left">
<SPAN>Hello</SPAN>
</td>
<td align="left">
World is not enough
</td>
</tr>
</table>
<div><a href="aa" id="id">this is a test</a></div>
<script>
var element = document.getElementById('foo');
seg = document.createElement('SPAN');
root_1_SPAN_1_text = document.createTextNode('new text');
seg.appendChild(root_1_SPAN_1_text);
if (element.hasChildNodes())
{
var children = element.childNodes;
for (var i = 0; i < children.length; i++)
{
if(children[i].nodeName=="#text")
{
continue;
}
element.removeChild(children[i]);
element.appendChild(seg);
};
};
</script>
</BODY>
</HTML>
謝謝