我想获取一个元素的所有后代文本节点,作为jQuery集合。 最好的方法是什么?
#1楼
也可以这样完成:
var textContents = $(document.getElementById("ElementId").childNodes).filter(function(){
return this.nodeType == 3;
});
上面的代码从给定元素的直接子级子节点中过滤textNodes。
#2楼
对我来说,普通的老式.contents()
似乎可以返回文本节点,只需要小心选择器,以便您知道它们将是文本节点。
例如,这用pre
标签将TD的所有文本内容包装在了我的表中,没有问题。
jQuery("#resultTable td").content().wrap("<pre/>")
#3楼
jQuery.contents()
可与jQuery.filter
一起使用以查找所有子文本节点。 稍作改动,您就可以找到孙子文本节点。 无需递归:
$(function() { var $textNodes = $("#test, #test *").contents().filter(function() { return this.nodeType === Node.TEXT_NODE; }); /* * for testing */ $textNodes.each(function() { console.log(this); }); });
div { margin-left: 1em; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="test"> child text 1<br> child text 2 <div> grandchild text 1 <div>grand-grandchild text 1</div> grandchild text 2 </div> child text 3<br> child text 4 </div>
#4楼
由于某些原因, contents()
对我不起作用,所以如果它对您不起作用,这是我做的一个解决方案,我创建了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
这是跨浏览器,代码中包含一个小的Array.indexOf
。
#5楼
我得到了很多带有可接受的过滤器功能的空白文本节点。 如果仅对选择包含非空格的文本节点感兴趣,请尝试将条件条件的nodeValue
添加到filter
函数中,例如简单的$.trim(this.nodevalue) !== ''
:
$('element')
.contents()
.filter(function(){
return this.nodeType === 3 && $.trim(this.nodeValue) !== '';
});
或者,为了避免出现内容看起来像空白但不是空白的奇怪情况(例如,软连字符­
字符,换行符\\n
,制表符等),您可以尝试使用正则表达式。 例如, \\S
将匹配任何非空白字符:
$('element')
.contents()
.filter(function(){
return this.nodeType === 3 && /\S/.test(this.nodeValue);
});
来源:oschina
链接:https://my.oschina.net/u/3797416/blog/3165692