17

How can I remove an element but not the content inside that element?

<a href="#">
    <span>
        <img src="pic-1.jpg"/>
    </span>
</a>

I want to remove the span that wraps the image.

So I can get,

<a href="#">

    <img src="pic-1.jpg"/>

</a>
Run
  • 54,938
  • 169
  • 450
  • 748
  • Possible duplicate of [Remove a HTML tag but keep the innerHtml](http://stackoverflow.com/questions/4232961/remove-a-html-tag-but-keep-the-innerhtml) – Dzyann Mar 01 '17 at 13:18

4 Answers4

42

You need unwrap

$('img').unwrap();
dfsq
  • 191,768
  • 25
  • 236
  • 258
10
$(document).ready(function(){
  $span = $('span');
  $span.replaceWith($span.html());
}); 

see example http://jsfiddle.net/vikastyagi87/Xaa39/6/

thecodedeveloper.com
  • 3,220
  • 5
  • 36
  • 67
  • I think this is the most complete answer because it also works for unwrapping text (not only DOM elements) – viery365 Mar 29 '17 at 02:25
4

The jQuery function unwrap() is what you're looking for:

Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place.

Check out the API doc page for more information.

Michelle Tilley
  • 157,729
  • 40
  • 374
  • 311
1

You'll have to modify your HTML architecture a bit here:

<a href="#" id="my_href">
    <span id="my_span">
        <img src="pic-1.jpg"/>
    </span>
</a>

jQuery solution:

$("#my_href").html($("#my_span").html());

Non jQuery solution:

document.getElementById("my_href").innerHTML = document.getElementById("my_span").innerHTML;
Elliot Bonneville
  • 51,872
  • 23
  • 96
  • 123