javascript - 从数组中查找包含指定单词的 div 的类名

标签 javascript arrays google-chrome-extension getelementsbyclassname

这是 Google 扩展程序

我有一组单词,我尝试将其与 Twitter feed 上的现有单词进行匹配。

如果找到匹配项,则会在控制台中打印“exists”。

我正在尝试从我的spoiled数组中查找包含指定单词的元素的类名称。

我知道它将是一个 div,因为推文总是放入 div 中,但如何在纯 JavaScript 中找到类名?

//array with all the censor words 
var spoiled = ["terrible", "but", "pasta"];

//checks through every word of array and page
var result = spoiled.every(function(word) {
    return document.documentElement.innerText.indexOf(word) > -1;
});

// Checking page title
if (document.title.indexOf("Twitter") != -1) {

    //checks if every word of array is on page
    if (result) { 
        //if so do this

        console.log("exists");

    } else{
        console.log("not exist");
    }
}

我需要类名的原因是因为我 future 的计划是在包含数组中单词的 div 上放置一个图像。

最佳答案

The reason I need the class name is because my future plan is to place an image over the div that contains the words in my array.

听起来你想要获取对 div 的引用,而不是它的类(但是一旦你有了对它的引用,你就可以从 .className 获取它的类> 如果您确实需要的话)。

这意味着您需要遍历文档树中的节点,而不是使用 innerText,这非常简单。对于 this answer我发布了一个通用的“在 DOM 中查找匹配节点”函数,该函数接受谓词函数,因此我们可以将它与谓词一起使用,以检查元素中的文本节点是否存在数组中的单词。

您在问题中使用了Array#every,只有当所有迭代都返回真值时,它才会返回true;下面我使用 Array#some 来标记已找到其中的任何。包含任何单词的元素都会添加一个类,highlight,它会在它们后面放置一个黄色背景:

// The searcher function
function domFind(element, predicate, results = []) {
  if (!element.children) {
    throw new Error("Starting node must be an element or document");
  }
  if (predicate(element)) {
    results.push(element);
  }
  if (element.children && element.children.length) {
    [...element.children].forEach(child => {
      domFind(child, predicate, results);
    });
  }
  return results;
}
// Our words
let array = ["terrible", "but", "pasta"];
// Do our search with a predicate
let elements = domFind(document, element => {
  return Array.from(element.childNodes).some(n => {
    return n.nodeName.toLowerCase() != "script" &&
           n.nodeType == 3 &&
           array.some(word => n.nodeValue.indexOf(word) != -1);
  });
});
// We have the array of elements; add a class to them
elements.forEach(e => { e.classList.add("highlight"); });
.highlight {
  background-color: yellow;
}
<div>blah blah</div>
<div>this is terrible!</div>
<div>lorem ipsum</div>
<div>
  <div>
    <div>no fate but what we make</div>
  </div>
  <div>la la la</div>
  <div>mmmmmm pasta</div>
</div>
<div>foo</div>

由于这是一个 Chrome 扩展程序,因此我很高兴使用 ES2015 来实现上述目的。

关于javascript - 从数组中查找包含指定单词的 div 的类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38811304/

相关文章:

java - 用java从txt文件中读取迷宫

javascript - 如何在 Chrome 扩展中从本地存储读取和写入 div 的内容?

javascript - 如何通过 chrome 扩展获取所有 CSS 和 Javascript 文件

javascript - 登录代码在 Internet Explorer 中不起作用,但在 Chrome 和 Firefox 中起作用

javascript - JavaScript 中的字节计数

javascript - 在数组中找到匹配项并用 jQuery 替换它

python - Numpy 截断?

javascript - 如何循环处理请求的 javascript 页面?

javascript - 为什么 Cytoscape 在这种特定情况下会进入 "infinite"循环?

javascript - 动态 html 和 javascript 函数