gtilflm gtilflm - 5 months ago 19
jQuery Question

jQuery Remove HTML element but leave the content

Is there a jQuery function (or just straight javascript) to turn

<span class="emphasis">15.9</span>
into
15.9
?

Basically I want to remove the
<span>
tag but leave the stuff that's inside the tag.

Answer

Yes, it's called unwrap. You call it on the nodes you want to unwrap, so in your case, we'd call it on $(".emphasis").contents():

$(".emphasis").contents().unwrap();

Example:

// Show the content of the container prior to unwrapping
console.log("before unwrapping: " + $("#container").html());

// Unwrap
$(".emphasis").contents().unwrap();

// After unwrapping
console.log("after unwrapping: " + $("#container").html());
<div id="container">
  <span class="emphasis">15.9</span>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Example for when there are elements within the span:

// Show the content of the container prior to unwrapping
console.log("before unwrapping: " + $("#container").html());

// Unwrap
$(".emphasis").contents().unwrap();

// After unwrapping
console.log("after unwrapping: " + $("#container").html());
<div id="container">
  <span class="emphasis"><em>15</em>.9</span>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>