2

I have a structure like the following:

<form>
    <input type="text" />
    <input type="text" />
    ...
    <input type="radio" />
    <input type="whatever" />
    Here I have some text
</form>

I cannot change the structure of the HTML. I need to remove via Javascript the text inside the form, and the problem is to select it, since it is not wrapped inside any tag.

My solution (more a hack actually) using jQuery is the following

$('form').contents().filter(function(){
    return (this.toString() == '[object Text]')
}).remove();

but it's not very robust. In particular it fails on IE (all versions), where this.toString() applied to a chunk of text returns the text itself. Of course I could try

$('form').contents().filter(function(){
    return (this.toString() != '[object]')
}).remove();

but I'm looking for a better solution.

How am I supposed to remove the text?

Both a solution using jQuery or plain Javascript is good for me.

Andrea
  • 20,253
  • 23
  • 114
  • 183

4 Answers4

2

Try this, instead of just "this.toString()":

return (Object.prototype.toString.call(this) == '[object Text]');

You could also check the node type, but I never can remember how to do that; I'll go look it up but somebody's going to beat me to it :-)

edit told ya!

Pointy
  • 405,095
  • 59
  • 585
  • 614
2

You filter for this.nodeType == Node.TEXT_NODE. Take a look at this answer.

Community
  • 1
  • 1
Max Shawabkeh
  • 37,799
  • 10
  • 82
  • 91
2

If you use version 1.4 you can

var $temp= $('form').children().detach();
$('form').empty().append($temp);

It will remove all children elements, empty the form (the text..) and reinsert the elements..

the same in 1.3.x would require an additional step..

var $temp= $('<div />');
$('form').children().appendTo($temp);
$('form').empty().append($temp.children());

[Update] in regards to Andrea's comment

quoting jquery contents()

The .contents() and .children() methods are similar, except that the former includes text nodes as well as HTML elements in the resulting jQuery object.

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
  • This looks interesting, but does it work? I don't have time to try it right now. I'd think the text is counted as a child as well. – Andrea Mar 07 '10 at 11:17
  • @Andrea, both examples work in their respective versions.. updated answer to show documentations for it.. – Gabriele Petrioli Mar 07 '10 at 11:43
0

How about:

$('form').contents().filter(function(){
    return !this.outerHTML;
}).remove();
Joel
  • 19,175
  • 2
  • 63
  • 83