我在HTML页面上选择了所有节点,如下所示:
var all = $('*');
然后我遍历每个节点,检查每个节点是否有相关的文本值:
var newDom = all.map((i, node) => {
if ($(node).text()) {
var temp = $(node).text() + 'a';
$(node).text(temp);
}
});
我最终想在浏览器中查看被操纵的DOM。如果没有上述操作,all.html()
会产生所选的确切网页,正如我们所期望的那样。同时,newDom.html()
会产生以下错误:
Unhandled rejection Error: getaddrinfo ENOTFOUND on.ico on.ico:80
at errnoException (dns.js:28:10)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:79:26)
乍一看,为什么这不能像我上面那样工作?
答案 0 :(得分:1)
文本节点没有选择器,但是您可以编写递归函数将它们全部作为基于根节点的数组。然后你可以遍历数组并对文本节点执行操作,例如
/* Return all text nodes that are descendents of root as an array
** @param {DOMElement} root - node to start from, defaults to document.body
** @returns {Array} array of all text nodes that are descendents of root
*/
function getTextNodes(root) {
var root = root || document.body;
var textNodes = [];
// Don't process text inside these nodes
var elementsToIgnore = {'script':true};
if (root && root.nodeType == 1) {
Array.prototype.forEach.call(root.childNodes || [root], function(node) {
if (node.nodeType == 1 && node.tagName && !(node.tagName.toLowerCase() in elementsToIgnore)) {
textNodes = textNodes.concat(getTextNodes(node));
} else if (node.nodeType == 3){
textNodes.push(node);
}
});
} else if (root.nodeType == 3) {
textNodes.push(root);
}
return textNodes;
}
<p>Here is some text</p>
<ol>
<li>List item 1
<li>List item 2
<ol>
<li>List item 2.1
<li>List item 2.3
</ol>
<li>List item 3
</ol>
<textarea>Gets text in here too</textarea>
<br>
<button onclick="getTextNodes().forEach(function(node){node.data = node.data.replace(/s/g,'$')})">Replace all 's' with $</button>