2

Let's say I have this portion of HTML document:

<div>hello world <span id="test"></span></div>

In straight JavaScript, I need to replace the span with some HTML content contained in a string like '<span>other</span> yo <a href="www.google.ca">google</a>'

So the end result be like:

<div>hello world <span>other</span> yo <a href="www.google.ca">google</a></div>

The problem I'm facing is that the HTML string can contain any number of tags at its "root". So it is not a 1 to 1 replacement of tags.

I need to do that in straight JavaScript (no jQuery).

If anyone can help!

Thanks

2 Answers2

2

What is the reason you can't just set the innerHTML of <span id="test">? There's no harm in having the extra span...

If you really need to remove the outer span, you can just insert all the childNodes before it.

var html = '<span>other</span> yo <a href="www.google.ca">google</a>';

var removeMe = document.getElementById('test');
removeMe.innerHTML = html;

var child;
while(child = removeMe.childNodes[0]) {
    removeMe.parentNode.insertBefore(child, removeMe);
}

removeMe.parentNode.removeChild(removeMe);

See http://jsfiddle.net/4tLVC/1/

Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
  • I actually used your technique, but instead of working inside "removeMe", I created an unattached 'div' element and inserted the content into it, it might be a little faster since the dom objects are not attached to the main document.. But thank you very much it solved my problem :) – Mike Gleason jr Couturier Aug 18 '11 at 17:09
  • I am finally using this code: it seems I was loosing the ' yo ' text node with yours... http://jsfiddle.net/4zMha/ But thanks again! – Mike Gleason jr Couturier Aug 18 '11 at 17:16
  • Ahh, the bug is that i increases but the node is removed from the list, so it gets skipped, fixed the code and the jsfiddle – Ruan Mendes Aug 18 '11 at 17:55
0

can't you use

 var span = document.getElement...('test')
 div.getElementById('yourDiv').removeChild(span)

or actually you can do

span.parentNode.removeChild(span)

this should work to. After that

 div.innerHTML += 'your cool <span>content></span>'
mkk
  • 7,583
  • 7
  • 46
  • 62