如何更改页面中所有用户个人资料链接的颜色?

How to change the color of all user profile links in a page?

我正在尝试使用用户脚本在我的浏览器中更改每个用户个人资料的颜色 link。我的代码:

// ==UserScript==
// @name         Color changer
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  none
// @author       You
// @match        https://puzzling.stackexchange.com/questions/*
// @grant        none
// ==/UserScript==

let users = document.getElementsByClassName("user-details");

for (let user of users) {
    user.getElementsByTagName("a")[0].style.color = "red";
}

出于某种原因,

错误:

ERROR: Execution of script 'New Userscript' failed! user.getElementsByTagName(...)[0] is undefined

错误:

ERROR: Execution of script 'New Userscript' failed! user.getElementsByTagName(...)[0] is undefined

没有错误。


如何更改页面中所有用户个人资料link的颜色?

试试这个:

document.querySelectorAll('.user-details a').forEach( item => item.style.color = "red")

您可以使用“querySelectorAll”创建更复杂的 CSS 选择器。

用户评论附有不同的 CSS class,因此您需要:

document.querySelectorAll('.comment-user').forEach( item => item.style.color = "red")

或者 ... 如果你想同时执行这两项操作,你可以尝试用逗号分隔多个 CSS 查询:

document.querySelectorAll('.user-details a, .comment-user').forEach( item => item.style.color = "red")

Generally, you should NOT be using .getElementsByClassName() or .getElementsByTagName() in 2020 and especially not in a loop. As my other post gets into, these are some of the earliest DOM querying methods and they return "live" node lists, which can be costly, especially when used in conjunctions with a loop. .querySelectorAll() 是现代的替代品,也是您真正应该使用的。

您只需要正确查询任何 user-details 元素的所有 <a> 后代并遍历结果,为每个元素添加一个新的 class (您还应该尽可能避免内联样式,因为它们会导致代码重复、扩展性差且难以覆盖)。相反,使用 CSS classes,它们很容易添加和删除。

document.querySelector(".user-details a").forEach(function(item){
  item.classList.add("newColor");
});

当然,请确保您在 CSS:

中定义了 newColor class
.newColor { color: someColorYouWant; }