removeChild and appendChild for Span

J

JehanNYNJ

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.
 
R

RobB

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top