user105165
user105165

Reputation: 93

removing and appending a node

I want to remove below span elements from the div (<div id='foo'>) and append newly created nodes instead each of them.

I am using a loop to traverse all the children of the div, and for each node found I am removing it with removeChild and append an newly created node.

I am getting o/p as

<div id='foo'>
    <SPAN>new text</SPAN>
</div>

I want the o/p as follows

 <div id='foo'>
    <SPAN>new text</SPAN>
    <SPAN>new text</SPAN>
    <SPAN>new text</SPAN>
 </div>

Code for the problem is as follows

<!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>

Thanks in advance

Upvotes: 0

Views: 278

Answers (1)

Greg
Greg

Reputation: 321588

You're re-appending the same node each time, which just moves it (it doesn't copy it)

Change this:

element.appendChild(seg);

to this

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

Upvotes: 2

Related Questions