更新时间:2023-02-19 17:07:51
以下将让你所有的文本节点包含在匹配元素中:
The following will get you all text nodes that are contained within a matching element:
function getTextNodes(root, tagNamesArray) {
var textNodes = [];
var regex = new RegExp("^(" + tagNamesArray.join("|") + ")$", "i");
var insideMatchingElement = false;
function getNodes(node, insideMatchingElement) {
if (node.nodeType == 3 && insideMatchingElement) {
textNodes.push(node);
} else if (node.nodeType == 1) {
var childrenInsideMatchingElement = insideMatchingElement || regex.test(node.nodeName);
for (var child = node.firstChild; child; child = child.nextSibling) {
getNodes(child, childrenInsideMatchingElement);
}
}
}
getNodes(root);
return textNodes;
}
var textNodes = getTextNodes(document.body, ["blockquote","em","h4","h6","p"]);