我选择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)乍一看,为什么这不像我上面提到的那样有效呢?
发布于 2016-09-06 23:11:59
没有文本节点的选择器,但是您可以编写一个递归函数来将它们全部作为基于根节点的数组。然后,您可以遍历数组并对文本节点进行填充。
/* 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>
https://stackoverflow.com/questions/39339791
复制相似问题