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


当前回答

也可以这样做:

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

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

其他回答

也可以这样做:

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

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

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

代码:

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

用法:

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

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

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

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

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

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

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