How to unwrap text using jQuery?

前端 未结 5 1749
我寻月下人不归
我寻月下人不归 2020-12-08 11:18

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

For instance, how to transform this HTML

A sentence with bold

相关标签:
5条回答
  • 2020-12-08 11:38

    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();
    
    0 讨论(0)
  • 2020-12-08 11:45

    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 讨论(0)
  • 2020-12-08 11:46

    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,''); }); 
    
    0 讨论(0)
  • 2020-12-08 11:46

    To unwrap only text and nothing else you could use:

    $("b").replaceWith($("b").text());
    
    0 讨论(0)
  • 2020-12-08 11:58

    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.

    0 讨论(0)
提交回复
热议问题