Remove text with jQuery

后端 未结 5 888
生来不讨喜
生来不讨喜 2020-11-27 06:59

Is there a way to remove text that is not wrapped in any tag using jQuery

This is some text

This is \"unwrapped\" text //to be removed &
相关标签:
5条回答
  • 2020-11-27 07:21

    Wrapping it in a DOM element would mean jQuery can find it:

    eg:

    var text = 'This is "unwrapped" text';
    
    $("div:contains('" + text + "')").remove();
    

    or just:

    $('p').next().remove();
    
    0 讨论(0)
  • 2020-11-27 07:23

    fwiw..

    <div class="parent-element">
    <p>This is some text</p>
    This is "unwrapped" text //to be removed
    <span>some more text</span>
    </div>
    

    via CSS:

    .parent-element { font-size: 0px; }
    .parent-element p { font-size: 12px; }
    .parent-element span { font-size: 14px; }
    
    0 讨论(0)
  • 2020-11-27 07:33

    Using the answer from this question:

    $(elem)
      .contents()
      .filter(function() {
        return this.nodeType == 3; //Node.TEXT_NODE
      }).remove();
    
    0 讨论(0)
  • 2020-11-27 07:35

    First, you can wrap them with dummy spans:

    $("body").contents()
        .filter(function(){ return this.nodeType != 1; })
        .wrap("<span class='orphan'/>");
    

    Now you can remove them easily:

    $('span.orphan').remove();
    
    0 讨论(0)
  • 2020-11-27 07:35

    It's amazing but at the same time the following code doesn't work

    $("div.myClass:has(img)").contents().filter(":text").remove();
    

    and the code from the first post works

    $("div.myClass:has(img)")
      .contents()
      .filter(function() {
        return this.nodeType == 3; //Node.TEXT_NODE
      }).remove();
    

    It's important to remeber! jQuery 1.8.3.

    And first of all I remember that innerHTML manipulation works much more faster than this approach!

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