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
  • 51,293
  • 159
  • 419
  • 719
  • 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
  • 187,712
  • 24
  • 229
  • 250
10
$(document).ready(function(){
  $span = $('span');
  $span.replaceWith($span.html());
}); 

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

thecodedeveloper.com
  • 3,158
  • 5
  • 35
  • 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
  • 154,130
  • 39
  • 369
  • 310
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
  • 49,322
  • 23
  • 92
  • 122