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或更早版本,則上述代碼將無效。為了解決這個問題,更換addBack()
用andSelf()
。andSelf()
不贊成addBack()
從1.8開始。
與純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);