Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unwrap text using jQuery?

Tags:

html

jquery

How to unwrap a text from a HTML tag using jQUery?

For instance, how to transform this HTML

<p>A <i>sentence</i> with <b>bold words</b>.</p>

into (i.e. remove the bold tags)

<p>A <i>sentence</i> with bold words.</p>

using only jQuery and no regex?

like image 826
czuk Avatar asked Mar 09 '10 12:03

czuk


3 Answers

You can do this:

  $("b").each(function() {
    $(this).replaceWith(this.childNodes);
  });

Note: this preserves whatever HTML you have inside where .text() might transform it.

If you wanted to quite literally just strip the <b></b> you can use Cheeso's answer a bit easier in jQuery 1.4+:

$("p").html(function(i,h){ return h.replace(/<b>/g,'').replace(/<\/b>/g,''); }); 
like image 83
Nick Craver Avatar answered Sep 18 '22 15:09

Nick Craver


I've become quite fond of wrapInner first and then unwrap.

For example, if you were trying to unwrap a hyperlink

<a id="anId" href="#">sample text</a>

then you can unwrap the hyperlink via

$('#anId').wrapInner('<span/>');
$('#anId span').unwrap();
like image 25
Benjamin Avatar answered Sep 19 '22 15:09

Benjamin


How you do it depends on the additional constraints in your situation.

There's no general way to unbold.

If the tags are always <b>, then you can do this

var h = $(elementSelector).html;
h = h.replace("<b>","");
h = h.replace("</b>","");
$(elementSelector).html(h);

I'm not sure why you don't like Regex.

like image 23
Cheeso Avatar answered Sep 17 '22 15:09

Cheeso