views:

40

answers:

4

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.

+2  A: 

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

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

Max Shawabkeh
A: 

How about:

$('form').contents().filter(function(){
    return !this.outerHTML;
}).remove();
Joel Potter
+2  A: 
Gaby
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
@Andrea, both examples work in their respective versions.. updated answer to show documentations for it..
Gaby
Thank you very much! I wish I could choose two correct answers...
Andrea