简体   繁体   中英

Selecting child text with jQuery

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.

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!

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

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.

How about:

$('form').contents().filter(function(){
    return !this.outerHTML;
}).remove();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM