27

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

<p>This is some text</p>

This is "unwrapped" text //to be removed

<span>some more text</span>

Thank you for your help

Peter
  • 127,331
  • 53
  • 180
  • 211
Dom
  • 3,126
  • 14
  • 46
  • 68

4 Answers4

52

Using the answer from this question:

$(elem)
  .contents()
  .filter(function() {
    return this.nodeType == 3; //Node.TEXT_NODE
  }).remove();
Community
  • 1
  • 1
Greg
  • 316,276
  • 54
  • 369
  • 333
  • 2
    Yes, the `Node` constructor function is not mandated to be visible at `window` level, and `TEXT_NODE` would normally be found only on the prototype, not the constructor. The ‘correct’ way would be `this.nodeType==this.TEXT_NODE`, however even that still doesn't work on IE, so typically you have to define your own `var TEXT_NODE= 3;`. – bobince Oct 15 '09 at 09:11
8

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();
Kobi
  • 135,331
  • 41
  • 252
  • 292
3

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; }
sime0n
  • 31
  • 1
2

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();
Dom
  • 61
  • 1
  • 3