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

0

2 Answers 2

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/

Sign up to request clarification or add additional context in comments.

3 Comments

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 :)
I am finally using this code: it seems I was loosing the ' yo ' text node with yours... jsfiddle.net/4zMha But thanks again!
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
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>'

1 Comment

apparently someone does not like me ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.