471,350 Members | 1,442 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,350 software developers and data experts.

removeChild and appendChild for Span

I need to clear out the HTML contents of a <span> element and then
re-add that element as a blank span.

Here is the code...

var elem = document.getElementById(spanId);

var deletedElem = elem.parentNode.removeChild(elem);
deletedElem.innerHTML = '<span id="'+spanId+'"></span>';
deletedElem.parentNode.appendChild(deletedElem);

This does not work. When I try to getElementById the second time the
function is called it does not find the span I added. Any suggestions?

Thanks in advance for any help.

Jul 23 '05 #1
1 3559
JehanN...@aol.com wrote:
I need to clear out the HTML contents of a <span> element and then
re-add that element as a blank span.

Here is the code...

var elem = document.getElementById(spanId);

var deletedElem = elem.parentNode.removeChild(elem);
deletedElem.innerHTML = '<span id="'+spanId+'"></span>';
deletedElem.parentNode.appendChild(deletedElem);

This does not work. When I try to getElementById the second time the
function is called it does not find the span I added. Any suggestions?
Thanks in advance for any help.


You're removing the child span:

var deletedElem = elem.parentNode.removeChild(elem);

....effectively 'detatching' it from the document; then...

deletedElem.parentNode.appendChild(...

....referencing its parent node for appending. No parent node to
reference.

If you just want to clear out the element's descendents, try -

var elem;
if (elem = document.getElementById(spanId))
{
while (elem.hasChildNodes())
elem.removeChild(elem.lastChild);
}

Should clean it up nicely.

Jul 23 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

2 posts views Thread by samuel.adam | last post: by
3 posts views Thread by sfeher | last post: by
5 posts views Thread by tader | last post: by
10 posts views Thread by r_ahimsa_m | last post: by
7 posts views Thread by ChuckB via WebmasterKB.com | last post: by
reply views Thread by XIAOLAOHU | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.