我想获得一个元素的所有后代文本节点,作为一个jQuery集合。最好的方法是什么?


当前回答

如果您想剥离所有标签,那么试试这个

功能:

String.prototype.stripTags=function(){
var rtag=/<.*?[^>]>/g;
return this.replace(rtag,'');
}

用法:

var newText=$('selector').html().stripTags();

其他回答

我也遇到过同样的问题,我是这样解决的:

代码:

$.fn.nextNode = function(){
  var contents = $(this).parent().contents();
  return contents.get(contents.index(this)+1);
}

用法:

$('#my_id').nextNode();

类似于next(),但也返回文本节点。

我得到了大量的空文本节点与接受的过滤器功能。如果你只对选择包含非空格的文本节点感兴趣,试着在你的过滤器函数中添加一个nodeValue条件,比如简单的$.trim(this.nodevalue) !== ":

$('element')
    .contents()
    .filter(function(){
        return this.nodeType === 3 && $.trim(this.nodeValue) !== '';
    });

http://jsfiddle.net/ptp6m97v/

或者避免奇怪的情况,内容看起来像空格,但不是(例如软连字符&shy;字符,换行符\n,制表符等),您可以尝试使用正则表达式。例如,\S将匹配任何非空白字符:

$('element')
        .contents()
        .filter(function(){
            return this.nodeType === 3 && /\S/.test(this.nodeValue);
        });
$('body').find('*').contents().filter(function () { return this.nodeType === 3; });

对我来说,普通的.contents()似乎可以返回文本节点,只是必须小心选择器,以便知道它们将是文本节点。

例如,它用pre标签包装了表中td的所有文本内容,没有任何问题。

jQuery("#resultTable td").content().wrap("<pre/>")

如果您想剥离所有标签,那么试试这个

功能:

String.prototype.stripTags=function(){
var rtag=/<.*?[^>]>/g;
return this.replace(rtag,'');
}

用法:

var newText=$('selector').html().stripTags();