Barney Szabolcs
Barney Szabolcs

Reputation: 12514

How to remove a span in-place?

I have the following input:

<p>
  <span class="highlight">
    Some text <b>that can have formatted components too</b>.
  </span>
  And some more text here of course.
</p>

And I want to achieve the following output:

<p>
    Some text <b>that can have formatted components too</b>.
    And some more text here of course.
</p>

I am using jquery and it has a .unwrap() function, but if I go $('.highlight').unwrap() it removes <p>. :(

Manually hacking the DOM seems like a hassle. Do you know any short solution?

Upvotes: 5

Views: 331

Answers (3)

Spokey
Spokey

Reputation: 10994

With the use of .contents() you'll get the elements inside of the parent element you want to remove.

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

Upvotes: 10

RGR
RGR

Reputation: 1571

You can simply can do this by using jQuery.

var cnt = $(".highlight").contents();

$(".highlight").replaceWith(cnt);

Quick links to the documentation:

Upvotes: 0

Mukesh Kumar
Mukesh Kumar

Reputation: 783

try replace with

$('.highlight').replaceWith(function() {
    return $(this).html();
});

Upvotes: 2

Related Questions