如何使用JavaScript编辑网站的HTML元素?

时间:2017-11-22 19:28:10

标签: javascript html

此HTML代码包含网站上的按钮:

<button ng-class="twoFactorAuthState()" ng-click="toggleTwoFactorAuth()" class="but-on-off on" data-functional-selector="game-settings-two-factor-auth">
    <span class="enabled">On</span>
    <span class="disabled">Off</span>
    <span class="cover"></span>
</button>

是否可以在Google Chrome的控制台窗口中使用JavaScript来编辑 on-on-off on but-off-off off ,并包含第一行末尾的?结果将如下所示:

<button ng-class="twoFactorAuthState()" ng-click="toggleTwoFactorAuth()" class="but-on-off off" data-functional-selector="game-settings-two-factor-auth" disabled="disabled">
    <span class="enabled">On</span>
    <span class="disabled">Off</span>
    <span class="cover"></span>
</button>

我可以使用Google Chrome中的Inspect Element选项进行这些更改,但我希望以编程方式实现此目标。我认为值得一提的是,这不是我的网站,因此我无法在源代码中添加任何脚本。

非常感谢任何帮助。我知道那里有很多有才华的人。

1 个答案:

答案 0 :(得分:-2)

您可以在控制台中尝试这样的事情。

var butOnOffElements = document.querySelectorAll('.but-on-off');

butOnOffElements.forEach(function(currentValue) {
  if (currentValue.classList.contains('on')) {
    //before replacing 'on' with 'off'
    console.log(currentValue.classList);

    //replace 'on' with 'off'
    currentValue.classList.remove('on');
    currentValue.classList.add('off');

    //after replacing 'on' with 'off'
    console.log(currentValue.classList);
  }
});
<button ng-class="twoFactorAuthState()" ng-click="toggleTwoFactorAuth()" class="but-on-off on" data-functional-selector="game-settings-two-factor-auth">
    <span class="enabled">On</span>
    <span class="disabled">Off</span>
    <span class="cover"></span>
</button> <br/>
<button ng-class="twoFactorAuthState()" ng-click="toggleTwoFactorAuth()" class="but-on-off off" data-functional-selector="game-settings-two-factor-auth">
    <span class="enabled">On</span>
    <span class="disabled">Off</span>
    <span class="cover"></span>
</button>

以下是MDN的文档,如果您需要研究每种方法的工作原理:

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach

https://developer.mozilla.org/en-US/docs/Web/API/Element/classList