getElementsByClassName不适用于Chrome

时间:2018-01-08 18:04:37

标签: javascript google-chrome

我正在尝试创建一个隐藏div某个类的Chrome扩展程序,但遗憾的是我无法让它工作:

我的manifest.json

{
  "manifest_version": 2,

  "name": "DivFilter",
  "description": "This extension allows the user to filter StackOverflow questions.",
  "version": "1.0",

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": [
    "activeTab"
  ]
}

我的popup.html

<html>
  <head>
    <title>SO Filter</title>
    <script src="popup.js"></script>
  </head>
  <body>
    <h1>SO Filter</h1>
    <button>Filter!</button>
  </body>
</html>

和我的popup.js

function filter() {
  var x = document.getElementsByClassName("question-summary narrow");
  console.log("Starting for-loop:");
  console.log(x);
  for (var i = 0; i < x.length; i++) {
    console.log(x[i]);
    var style = window.getComputedStyle(x[i]);

    if (style.display === "none") {
      x[i].style.display = "block";
    } else {
      x[i].style.display = "none";
    }
  }
}

document.addEventListener('DOMContentLoaded', function() {
  document.querySelector('button').addEventListener('click', filter);
});

点击https://stackoverflow.com/上的按钮时,会记录以下内容:

enter image description here

我不明白为什么length为0,因为在检查页面时它会清楚地显示我正在搜索的类div

enter image description here

我已经在SO上阅读了很多关于此的帖子,但到目前为止我还没能解决我的问题......

0 个答案:

没有答案