首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >操纵jQuery节点的文本值

问操纵jQuery节点的文本值
EN

Stack Overflow用户
提问于 2016-09-06 02:30:32
回答 1查看 58关注 0票数 2

我选择HTML页面上的所有节点,如下所示:

代码语言:javascript
复制
var all = $('*');

然后遍历每个节点,检查每个节点是否有关联的文本值:

代码语言:javascript
复制
var newDom = all.map((i, node) => {
  if ($(node).text()) {
     var temp = $(node).text() + 'a';
     $(node).text(temp);
  }
});

我最终希望在浏览器中查看被操纵的DOM。如果没有上面的操作,all.html()就会生成所选的确切网页,正如我们所期望的那样。同时,newDom.html()会产生以下错误:

代码语言:javascript
复制
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)

乍一看,为什么这不像我上面提到的那样有效呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-09-06 23:11:59

没有文本节点的选择器,但是您可以编写一个递归函数来将它们全部作为基于根节点的数组。然后,您可以遍历数组并对文本节点进行填充。

​

代码语言:javascript
复制
/* 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;
}
代码语言:javascript
复制
 <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>

​

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39339791

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档