Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 779
Barney Szabolcs Avatar asked May 06 '13 09:05

Barney Szabolcs


People also ask

How do I remove span?

To unwrap the element and keep its content, right-click on the element (or select More actions from the selected element menu) to open the context menu and there select Transform -> Remove outer span.

Can you style a span?

The span tag is just like a div, which is used to group similar content so it can all be styled together. But span is different in that it is an inline element, as opposed to div , which is a block element. Also, keep in mind that span itself does not have any effect on its content unless you style it.

How does span work?

The <span> tag is an inline container used to mark up a part of a text, or a part of a document. The <span> tag is easily styled by CSS or manipulated with JavaScript using the class or id attribute. The <span> tag is much like the <div> element, but <div> is a block-level element and <span> is an inline element.

When to use span in HTML?

Span tags are used on small segments of text, links, images, and other HTML elements that appear inline with the surrounding content. To summarize, a div tag creates a block-level element while a <span> tag wraps around an inline element.


2 Answers

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

$(".highlight").contents().unwrap();
like image 65
Spokey Avatar answered Sep 21 '22 17:09

Spokey


try replace with

$('.highlight').replaceWith(function() {
    return $(this).html();
});
like image 24
Mukesh Kumar Avatar answered Sep 25 '22 17:09

Mukesh Kumar