我想获得一个元素的所有后代文本节点,作为一个jQuery集合。最好的方法是什么?
当前回答
$('body').find('*').contents().filter(function () { return this.nodeType === 3; });
其他回答
如果您想剥离所有标签,那么试试这个
功能:
String.prototype.stripTags=function(){
var rtag=/<.*?[^>]>/g;
return this.replace(rtag,'');
}
用法:
var newText=$('selector').html().stripTags();
$('body').find('*').contents().filter(function () { return this.nodeType === 3; });
Jauco在评论中发布了一个很好的解决方案,所以我在这里复制它:
$(elem)
.contents()
.filter(function() {
return this.nodeType === 3; //Node.TEXT_NODE
});
jQuery对此没有一个方便的函数。您需要结合contents()和find(),前者只提供子节点,但包含文本节点,后者提供所有子代元素,但不提供文本节点。以下是我想到的:
var getTextNodesIn = function(el) {
return $(el).find(":not(iframe)").addBack().contents().filter(function() {
return this.nodeType == 3;
});
};
getTextNodesIn(el);
注意:如果您使用的是jQuery 1.7或更早版本,上面的代码将无法工作。为了解决这个问题,用andSelf()替换addBack()。andSelf()已弃用,从1.8开始改用addBack()。
与纯DOM方法相比,这有点低效,并且必须包含一个丑陋的解决方法,以解决jQuery重载contents()函数的问题(感谢评论中的@rabidsnail指出这一点),因此这里是使用简单递归函数的非jQuery解决方案。includeWhitespaceNodes参数控制是否在输出中包含空白文本节点(在jQuery中,它们会自动过滤掉)。
更新:修正includeWhitespaceNodes为假时的错误。
function getTextNodesIn(node, includeWhitespaceNodes) {
var textNodes = [], nonWhitespaceMatcher = /\S/;
function getTextNodes(node) {
if (node.nodeType == 3) {
if (includeWhitespaceNodes || nonWhitespaceMatcher.test(node.nodeValue)) {
textNodes.push(node);
}
} else {
for (var i = 0, len = node.childNodes.length; i < len; ++i) {
getTextNodes(node.childNodes[i]);
}
}
}
getTextNodes(node);
return textNodes;
}
getTextNodesIn(el);
也可以这样做:
var textContents = $(document.getElementById("ElementId").childNodes).filter(function(){
return this.nodeType == 3;
});
上面的代码从给定元素的直接子节点中过滤textnode。