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


当前回答

无论标记名称如何,这都可以完成工作。选择你的父母。

它为父节点和子节点提供了一个无重复的字符串数组。

$('parent')
.find(":not(iframe)")
.addBack()
.contents()
.filter(function() {return this.nodeType == 3;})
//.map((i,v) => $(v).text()) // uncomment if you want strings

其他回答

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

代码:

$.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。

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

功能:

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

用法:

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

我得到了大量的空文本节点与接受的过滤器功能。如果你只对选择包含非空格的文本节点感兴趣,试着在你的过滤器函数中添加一个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);
        });

如果您可以假设所有的子节点不是元素节点就是文本节点,那么这就是一种解决方案。

获取所有子文本节点为jquery集合:

$('selector').clone().children().remove().end().contents();

获取删除非文本子元素的原始元素的副本:

$('selector').clone().children().remove().end();