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.

Lucas
  • 16,930
  • 31
  • 110
  • 182

4 Answers4

8

Plain JS using a textNode:

var span = document.getElementById("foo");
span.parentNode.replaceChild(document.createTextNode("bar"), span);
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 1
    *this* is http://stackoverflow.com/questions/843680/how-to-replace-dom-element-in-place-using-javascript – digitalextremist Feb 01 '14 at 10:15
  • What are you saying? My answer is plain JS as requested. jQuery was ok too – mplungjan Feb 01 '14 at 10:16
  • I am saying your answer is the answer given in http://stackoverflow.com/questions/843680/how-to-replace-dom-element-in-place-using-javascript – digitalextremist Feb 01 '14 at 10:17
  • 1
    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 – mplungjan Feb 01 '14 at 10:19
5

.replaceWith ...

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

jQuery: Documentation »

digitalextremist
  • 5,952
  • 3
  • 43
  • 62
4

use .unwrap():

$("#foo").contents().unwrap();
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
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/

Ram
  • 143,282
  • 16
  • 168
  • 197