操作jQuery节点的文本值

Manipulate text value of jQuery nodes

本文关键字:文本 节点 jQuery 操作      更新时间:2023-09-26

我选择了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)

乍一看,为什么这可能不工作,因为我有上面?

文本节点没有选择器,但是您可以编写一个递归函数,将它们作为基于根节点的数组获取。然后你可以循环遍历数组并对文本节点做一些事情,例如

/* 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>