【问题标题】:Problems selecting a div depending on text inside根据内部文本选择 div 的问题
【发布时间】:2020-03-22 09:02:56
【问题描述】:

我一直在与 puppeteer 合作一个项目,到目前为止进展顺利,直到尝试根据他们的文本本地化 div。 我不能使用 div id、名称或类,我需要通过其中的文本找到它。 我的想法是创建一个包含我需要查找的所有文本的数组,然后循环遍历 div 以查找与数组中的任何文本匹配的文本。 有人可以帮我找到解决方案吗?谢谢!

【问题讨论】:

标签: javascript css-selectors puppeteer


【解决方案1】:

使用 vanilla javascript(无 JS 库)相对简单:

// Get an array of all <divs>:
let allDivs = [... document.getElementsByTagName('div')];


// Loop through allDivs, checking the text of each one:
allDivs.forEach((div) => {

  let textInsideDiv = div.textContent;

  // THE REST OF YOUR CODE HERE
  // if (myArrayOfText.indexOf(textInsideDiv) > -1)) { etc.}
}

【讨论】:

  • 嘿!感谢您的回答,但我有一个问题,“让 textInsideDiv = div.textContent”在那部分,我想指出我必须在 div 中找到哪些文本?
  • 那是indexOf 行,注释掉,朝向底部。翻译成英文,if (myArrayOfText.indexOf(textInsideDiv) &gt; -1)的意思是If the textInsideDiv matches any of the elements inside myArrayOfText
  • 哦,好的,这就解释了,我试试,我会告诉你怎么回事,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-10
  • 2018-01-21
  • 1970-01-01
  • 1970-01-01
  • 2011-01-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多