5

So assuming I had this:

<span id="foo">bar</span>

I want to replace it with this:

bar

In other words, I want to remove the span from the DOM, and insert its contents in its place.

How can I achieve this, using code as minimal as possible? I want to use pure JavaScript, but jQuery's fine as well.

Thanks.

2
  • @mplungjan not quite a duplicate, but close. The OP includes jQuery, and as my answer shows, there is another way ( with jQuery ) Commented Feb 1, 2014 at 10:12
  • Change the link in the answer with a textnode and it is, as my answer shows Commented Feb 1, 2014 at 10:17

4 Answers 4

8

Plain JS using a textNode:

var span = document.getElementById("foo");
span.parentNode.replaceChild(document.createTextNode("bar"), span);
Sign up to request clarification or add additional context in comments.

4 Comments

What are you saying? My answer is plain JS as requested. jQuery was ok too
I am saying your answer is the answer given in stackoverflow.com/questions/843680/…
My answer is the modified answer using textnode. It was written by hand and is using the same syntax, but is answered since the answer in the duplicate (which I linked to) was not using a textnode as you mentioned in the comment to my duplicate link
5

.replaceWith ...

$( "#foo" ).replaceWith( "bar" );

jQuery: Documentation »

Comments

4

use .unwrap():

$("#foo").contents().unwrap();

1 Comment

after replacing the contents with "bar"
1

Using jQuery you can replace the element with it's contents using replaceWith method and childNode property, this will work in case that your element has more than one descendant Node:

$('#foo').replaceWith(function() {
   return this.childNodes;
});

Using pure JavaScript something like the following should work:

var foo = document.getElementById('foo');

while(foo.childNodes.length)
   foo.parentNode.insertBefore(foo.childNodes[0], foo);

foo.parentNode.removeChild(foo);

http://jsfiddle.net/mM54V/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.