开发者

How to unwrap text using 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 开发者_如何学JAVAjQuery 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.


To unwrap only text and nothing else you could use:

$("b").replaceWith($("b").text());


$('b').contents().unwrap();

Target the contents of the element that you've selected and unwrap them.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜