tags:

views:

216

answers:

3

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

+2  A: 

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
+4  A: 

Using the answer from this question:

$(elem)
  .contents()
  .filter(function() {
    return this.nodeType == 3; //Node.TEXT_NODE
  }).remove();
Greg
yours is probably better than mine, but I'm not sure Node.TEXT_NODE works on all browsers.
Kobi
Mmm possibly...edited
Greg
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
A: 

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