如何对所有<a> elements on a page whose href&#39;s appear in an array? (javascript)

时间:2018-12-04 23:03:02

标签: javascript loops google-chrome-extension href

I am making a Google Chrome extension that creates an array of links on a page that meet a certain condition. I want to write a function that then loops through all the elements (links) on the page and if any of their href's appear on the array of hrefs that my previous function produced, I want to surround that link with a red border. This is what I've written so far but it doesn't work. The way I've tried to do it before the current implementation was assign a class to each of the elements that appear in the array and then inject a css script into the page that applies the red border to all elements with that class.

function highlight(linkArray)
{
  var allLinks = chrome.tabs.executeScript(null,{code:"document.getElementsByTagName('a')"});
  for (var i = 0; i < allLinks.length; i++)
  {
    chrome.tabs.executeScript(null,{code:"document.getElementsByTagName('A')[i].style.border='2px solid red'"});
  }
}
// Below is a rough idea of another way I've tried to got about it but it also doesnt work
// var allLinks = chrome.tabs.executeScript(null,{code:"document.getElementsByTagName('A')"});
// for (var i = 0; i < allLinks.length; i++) {
//   for (var j = 0; j < linkArray.length; j++) {
//       if (allLinks[i] == linkArray[j].href) {
//         chrome.tabs.executeScript(null,{code:"document.querySelectorAll('a[href=`${linkArray[i]}`]')[i].className += 'badLink'"});
//       }
//   }
// }

1 个答案:

答案 0 :(得分:1)

我建议您将linkArray组合成CSS选择器,如下所示:

a[href^="link1"], a[href^="link2"], ...

然后在document.querySelectorAll中使用此选择器来获取列出的链接并style

所以您的函数应如下所示:

function highlight() {
  var linkArray = ['bad', 'awful', 'horrible', 'dead'];

  // preparing the code as a string
  var code = `
    document.querySelectorAll(
      '${linkArray.map(l => `a[href^="${l}"]`).join(',')}'
    ).forEach(a => a.style.border = 'solid 2px red')
  `;

  // executing the code
  chrome.tabs.executeScript(null, {code: code});
}

以下代码段是一个有效的示例:

// Faking 'chrome.tabs.executeScript' to make it work in the snippet.
// You don't need it in your extension.
var chrome = {tabs: {executeScript: (_, {code}) => eval(code)}};

highlight();

function highlight() {
  var linkArray = ['bad', 'awful', 'horrible', 'dead'];

  // preparing the code as a string
  var code = `
    document.querySelectorAll(
      '${linkArray.map(l => `a[href^="${l}"]`).join(',')}'
    ).forEach(a => a.style.border = 'solid 2px red')
  `;
  
  // executing the code
  chrome.tabs.executeScript(null, {code: code});
}
<a href="bad">Bad link</a>
<a href="ok">OK link</a>
<a href="awful">Awful link</a>
<a href="horrible">Horrible link</a>
<a href="good">Good link</a>
<a href="nice">Nice link</a>
<a href="dead">Dead link</a>
<a href="bad#2">Bad#2 link</a>