【问题标题】:Changing a class name in HTML using Tampermonkey使用 Tampermonkey 更改 HTML 中的类名
【发布时间】:2021-06-06 15:14:34
【问题描述】:

所以我正在查看我朋友编写的网站的代码,我想知道是否有一种方法可以使用 Tampermonkey 将具有特定类名的所有元素更改为另一个。

这是我目前的代码:

// @name         ClassName Change
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Change class names for website review
// @author       Me
// @match        https://example.com/*
// @grant        none
// @include      https://example.com/*
// ==/UserScript==


const change = document.getElementsByClassName("svg-sprite-vs top-point-empty");

change.className = "svg-sprite-vs top-point-full";

“tampermonkey script running”标记显示在工具栏中,表示脚本正在运行,但类名没有改变,网站的外观也没有改变。

有什么建议吗?

【问题讨论】:

    标签: javascript html tampermonkey


    【解决方案1】:

    多个类可以应用于多个元素,并且可以有多个元素共享一个类。

    你会想在一个循环中遍历它们,这样你就可以接触到它们。

    此外,您可以使用 Element.classList,这是一种很好的方式来更改您想要的内容,而不会与其他类混淆。

    document.querySelectorAll('.svg-sprite-vs.top-point-empty').forEach(elem => {
       elem.classList.remove('top-point-empty');
       elem.classList.add('top-point-full');
    });
    

    如果您想覆盖类,只需执行elem.setAttribute('class', 'svg-sprite-vs top-point-full')

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-03
      • 1970-01-01
      • 2016-07-20
      • 1970-01-01
      相关资源
      最近更新 更多