删除和附加节点

时间:2009-07-23 12:16:12

标签: javascript html dom

我想从spandiv)中移除以下<div id='foo'>元素,并添加新创建的节点,而不是每个元素。

我正在使用循环来遍历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>

提前致谢

1 个答案:

答案 0 :(得分:2)

每次重新附加相同的节点,只是移动它(它不会复制它)

改变这个:

element.appendChild(seg);

到这个

element.appendChild(seg.cloneNode(true));