Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove an element but not the content inside it?

Tags:

jquery

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>
like image 822
Run Avatar asked Mar 17 '12 18:03

Run


People also ask

How do I remove content from a tag?

Select the HTML element which need to remove. Use JavaScript remove() and removeChild() method to remove the element from the HTML document.

How do you delete an element in CSS?

You cannot remove an element from the DOM tree using CSS. You can only prevent it from being rendered in the layout with display: none ; doing so does not prevent it from responding to events or cause it to be ignored by CSS selectors such as + and :nth-child() .

How do you remove an element?

Removing an element using the removeChild() method First, select the target element that you want to remove using DOM methods such as querySelector() . Then, select the parent element of the target element and use the removeChild() method.


4 Answers

You need unwrap

$('img').unwrap();
like image 85
dfsq Avatar answered Oct 08 '22 19:10

dfsq


$(document).ready(function(){
  $span = $('span');
  $span.replaceWith($span.html());
}); 

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

like image 45
thecodedeveloper.com Avatar answered Oct 08 '22 19:10

thecodedeveloper.com


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.

like image 33
Michelle Tilley Avatar answered Oct 08 '22 19:10

Michelle Tilley


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;
like image 41
Elliot Bonneville Avatar answered Oct 08 '22 21:10

Elliot Bonneville