tags:

views:

83

answers:

4

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?

+2  A: 

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.

Cheeso
In 1.4 you can pass a function for this approach as well: `$("p").html(function(i, h) { h = h.replace(/<b>/g,''); return h.replace(/<\/b>/g,''); });`
Nick Craver
@Nick, he does mention not to use regex though ...
Gaby
@Gaby - Agreed, but if someone else comes across this and wants that solution, no harm in having it.
Nick Craver
@Nick, indeed ..
Gaby
Technically, I think a regular string.replace() uses a regex, no? It's just that I didn't use any regex codes in that string.
Cheeso
+1  A: 

To unwrap only text and nothing else you could use:

$("b").replaceWith($("b").text());
MBO
Urh, where have his <i> tags gone?
CResults
Note this isn't safe when you have other tags, if **any** HTML tag is inside `<b></b>` it will be lost.
Nick Craver
Note: Read question aloud one more time
MBO
@MBO - I did, and it says remove the bold tags, not strip everything else out, so noting that in case anyone uses this approach and gets unexpected behavior. You forget this question along with the rest of SO is found later by people trying to solve a slightly different problem. You're not always solving the just problem at hand, if there are side-effects, best to mention them. No offense intended, just something to keep in mind.
Nick Craver
+8  A: 

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,''); }); 
Nick Craver
A: 

I think relying solely on jQuery in this case needlessly complicates things. It would be easier to use the replace method which accepts either a normal string or a regular expression.

Using regex is generally the way to go in this case, because you want multiple substitutions which have roughly the same pattern.

mensch