我想获得一个元素的所有后代文本节点,作为一个jQuery集合。最好的方法是什么?
当前回答
如果您可以假设所有的子节点不是元素节点就是文本节点,那么这就是一种解决方案。
获取所有子文本节点为jquery集合:
$('selector').clone().children().remove().end().contents();
获取删除非文本子元素的原始元素的副本:
$('selector').clone().children().remove().end();
其他回答
我也遇到过同样的问题,我是这样解决的:
代码:
$.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。
我得到了大量的空文本节点与接受的过滤器功能。如果你只对选择包含非空格的文本节点感兴趣,试着在你的过滤器函数中添加一个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);
});
如果您想剥离所有标签,那么试试这个
功能:
String.prototype.stripTags=function(){
var rtag=/<.*?[^>]>/g;
return this.replace(rtag,'');
}
用法:
var newText=$('selector').html().stripTags();
jQuery.contents()可以与jQuery一起使用。筛选器以查找所有子文本节点。稍作改动,您还可以找到孙辈文本节点。不需要递归:
$(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>
js小提琴