首页 > 解决方案 > 通过 DOM 递归搜索以去除 innerText

问题描述

我需要递归搜索 DIV 层次结构并获取 innerText。我只能通过 ID 识别父母,但这是唯一一致的信息。我知道在该元素的子元素中有一个带有文本的 div。通过所有孩子和孩子的孩子递归地做到这一点的最佳方法是什么?

这是我得到的日志:

Found text: .rLshyf,.BmP5tf{padding-top:56px;padding-bottom:56px}
Found text: .w1C3Le,.BmP5tf,.G5NbBd{padding-left:112px;padding-right:112px;}
Found text: .G5NbBd{padding-bottom:56px}
Found text: .ROYx{display:flex;justify-content:space-between}
Found text: .SkmBxc{width:988px;margin-right:68px}
Found text: .EURV7d{font-weight:500;margin-top:-8px}
Found text: .j8epzd{height:192px;margin-top:16px}
Found text: .UYT3jb{width:100%;height:2px;margin-top:24px;margin-bottom:24px;background-color:#303030}
Found text: .z24g9c{margin-top:32px}
Found text: .GsVE9b{float:right}
Found text: .MUxGbd{font-size:28px;font-family:Roboto,sans-serif;line-height:40px;padding-top:2px;margin-bottom:-2px}
Found text: .MUxGbd.ITUZi{font-size:40px;line-height:48px}
Found text: .lyLwlc{color:#202124}
Found text: .aLF0Z{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}
Found text: .MUxGbd.v0nnCb{font-size:32px;line-height:48px;padding-top:6px;margin-bottom:-6px;}
Found text: .lEBKkf{display:-webkit-box;-webkit-box-orient:vertical;overflow:hidden}
Found text: .L6lOSd{color:rgba(255,255,255,.5) !important}
Found text: .L6lOSd svg{fill:rgba(255,255,255,.5);height:24px;width:24px;vertical-align:middle;margin-left:8px}
Found text: .L6lOSd:hover{background-color:#303030;color:rgba(255,255,255,1) !important}
Found text: .L6lOSd:hover svg{fill:rgba(255,255,255,1)}
Found text: .L6lOSd:focus{background-color:#303030;color:rgba(255,255,255,1) !important}
Found text: .L6lOSd:focus svg{fill:rgba(255,255,255,1)}
Found text: .MUxGbd.gbj1yb{font-size:24px;line-height:32px;padding-top:0px;margin-bottom:-8px}
Found text: .WZ8Tjf{color:#70757A}
Found text: .WZ8Tjf a:visited{color:#acacac}
Found text: Is iPhone 8 waterproof?
Found text: The iPhone 8 and 8 Plus is not waterproof — no smartphone is. However, as you stated yourself, they do have an IP67 rating for dust and water-resistance.
Found text: Source: damage - Does the iPhone 8 have any sort of water resistance or ...
Found text: window.onUrlClick=function(a){var b=a.getAttribute("data-url");a=a.getAttribute("data-follow-up-query");b?window.parent.postMessage({url:{href:b}},"*"):a&&window.parent.postMessage({query:{queryText:a}},"*")};
Found text: const ENTER_KEYCODE = 13;const ENTER = 'Enter';

我不明白为什么我会得到所有的内部样式文本。我怎样才能抓住可显示的文本内容?

标签: javascriptdom

解决方案


处理递归的最好方法是创建一个递归函数,所以这里是你可以从父级到树的方法。

function recurseEl(element) {
  if(element.childElementCount === 0) {
    element.textContent = '';
  } else {
    Array.from(element.children).forEach(child => {
      recurseEl(child);
    });
  }
}

function removeInnerText(elements) {
  recurseEl(element);
}

// Usage
const parentElement = document.getElementById('parent');
removeInnerText(parentElement);

如果树中仍有一个子节点,这会将相同的递归函数委托给树。当它碰到树中的叶子时,它运行替换函数。


推荐阅读