gtilflm
gtilflm

Reputation: 1465

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.

Upvotes: 0

Views: 109

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1074276

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>

Upvotes: 6

Patchesoft
Patchesoft

Reputation: 317

JavaScript:

var content = document.getElementByClassName("emphasis").innerHTML;

Upvotes: 0

grimmdude
grimmdude

Reputation: 374

Try

$('span.emphasis').replaceWith($('span.emphasis').text());

Upvotes: 2

Related Questions