I would like to get all descendant text nodes of an element, as a jQuery collection.(我想获取一个元素的所有后代文本节点,作为jQuery集合。)
What is the best way to do that?(最好的方法是什么?) ask by Christian Oudard translate from soI would like to get all descendant text nodes of an element, as a jQuery collection.(我想获取一个元素的所有后代文本节点,作为jQuery集合。)
What is the best way to do that?(最好的方法是什么?) ask by Christian Oudard translate from sojQuery doesn't have a convenient function for this.(jQuery对此没有方便的功能。)
You need to combinecontents()
, which will give just child nodes but includes text nodes, with find()
, which gives all descendant elements but no text nodes.(您需要将contents()
仅提供子节点但包括文本节点)与find()
,后者将提供所有后代元素,但不提供文本节点。) Here's what I've come up with:(这是我想出的:)
var getTextNodesIn = function(el) {
return $(el).find(":not(iframe)").addBack().contents().filter(function() {
return this.nodeType == 3;
});
};
getTextNodesIn(el);
Note: If you're using jQuery 1.7 or earlier, the code above will not work.(注意:如果您使用的是jQuery 1.7或更早版本,则上面的代码将不起作用。)
To fix this, replaceaddBack()
with andSelf()
.(要解决此问题,请用addBack()
替换andSelf()
。) andSelf()
is deprecated in favour of addBack()
from 1.8 onwards.(andSelf()
从1.8开始不推荐使用addBack()
。)
This is somewhat inefficient compared to pure DOM methods and has to include an ugly workaround for jQuery's overloading of its contents()
function (thanks to @rabidsnail in the comments for pointing that out), so here is non-jQuery solution using a simple recursive function.(与纯DOM方法相比,此方法效率低下,并且必须为jQuery的 content contents()
函数的重载提供一个丑陋的解决方法 (感谢注释中的@rabidsnail指出),因此这是使用简单递归的非jQuery解决方案功能。)
includeWhitespaceNodes
parameter controls whether or not whitespace text nodes are included in the output (in jQuery they are automatically filtered out).(includeWhitespaceNodes
参数控制输出中是否包含空格文本节点(在jQuery中,它们会自动过滤掉)。)
Update: Fixed bug when includeWhitespaceNodes is falsy.(更新:修复了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);