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?
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,''); });
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With