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


当前回答

$('body').find('*').contents().filter(function () { return this.nodeType === 3; });

其他回答

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

代码:

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

用法:

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

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

也可以这样做:

var textContents = $(document.getElementById("ElementId").childNodes).filter(function(){
        return this.nodeType == 3;
});

上面的代码从给定元素的直接子节点中过滤textnode。

Jauco在评论中发布了一个很好的解决方案,所以我在这里复制它:

$(elem)
  .contents()
  .filter(function() {
    return this.nodeType === 3; //Node.TEXT_NODE
  });

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

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

http://jsfiddle.net/ptp6m97v/

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

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