我想获得一个元素的所有后代文本节点,作为一个jQuery集合。最好的方法是什么?
当前回答
如果您想剥离所有标签,那么试试这个
功能:
String.prototype.stripTags=function(){
var rtag=/<.*?[^>]>/g;
return this.replace(rtag,'');
}
用法:
var newText=$('selector').html().stripTags();
其他回答
无论标记名称如何,这都可以完成工作。选择你的父母。
它为父节点和子节点提供了一个无重复的字符串数组。
$('parent')
.find(":not(iframe)")
.addBack()
.contents()
.filter(function() {return this.nodeType == 3;})
//.map((i,v) => $(v).text()) // uncomment if you want strings
出于某种原因,内容()不为我工作,所以如果它不为你工作,这是我做的解决方案,我创建了jQuery.fn.descendants的选项,以包括文本节点或不
使用
获取所有后代,包括文本节点和元素节点
jQuery('body').descendants('all');
使所有后代只返回文本节点
jQuery('body').descendants(true);
获取所有只返回元素节点的子节点
jQuery('body').descendants();
Coffeescript原创:
jQuery.fn.descendants = ( textNodes ) ->
# if textNodes is 'all' then textNodes and elementNodes are allowed
# if textNodes if true then only textNodes will be returned
# if textNodes is not provided as an argument then only element nodes
# will be returned
allowedTypes = if textNodes is 'all' then [1,3] else if textNodes then [3] else [1]
# nodes we find
nodes = []
dig = (node) ->
# loop through children
for child in node.childNodes
# push child to collection if has allowed type
nodes.push(child) if child.nodeType in allowedTypes
# dig through child if has children
dig child if child.childNodes.length
# loop and dig through nodes in the current
# jQuery object
dig node for node in this
# wrap with jQuery
return jQuery(nodes)
Javascript版本
var __indexOf=[].indexOf||function(e){for(var t=0,n=this.length;t<n;t++){if(t in this&&this[t]===e)return t}return-1}; /* indexOf polyfill ends here*/ jQuery.fn.descendants=function(e){var t,n,r,i,s,o;t=e==="all"?[1,3]:e?[3]:[1];i=[];n=function(e){var r,s,o,u,a,f;u=e.childNodes;f=[];for(s=0,o=u.length;s<o;s++){r=u[s];if(a=r.nodeType,__indexOf.call(t,a)>=0){i.push(r)}if(r.childNodes.length){f.push(n(r))}else{f.push(void 0)}}return f};for(s=0,o=this.length;s<o;s++){r=this[s];n(r)}return jQuery(i)}
完整的Javascript版本:http://pastebin.com/cX3jMfuD
这是一个跨浏览器的小数组。代码中包含indexOf polyfill。
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);
我得到了大量的空文本节点与接受的过滤器功能。如果你只对选择包含非空格的文本节点感兴趣,试着在你的过滤器函数中添加一个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);
});
Jauco在评论中发布了一个很好的解决方案,所以我在这里复制它:
$(elem)
.contents()
.filter(function() {
return this.nodeType === 3; //Node.TEXT_NODE
});