【问题标题】:No setAttribute or getAttribute in editing HTML in the Console Panel [duplicate]在控制台面板中编辑 HTML 时没有 setAttribute 或 getAttribute [重复]
【发布时间】:2018-08-23 06:14:27
【问题描述】:

我想尝试在 Chrome 的控制台面板中设置属性。

但不使用鼠标。像这样的例子: https://developers.google.com/web/updates/2015/08/edit-html-in-the-console-panel

我希望只写带有命令的JS-CODE,例如:

document.querySelectorAll(".serial-number").setAttribute("Value","dummy");

在控制台面板 Chrome 中,此功能 setAttribute 不可用。请问有没有其他方法可以通过设置属性来编写代码?

【问题讨论】:

  • 为什么要在元素集合上设置属性?我不知道集合对属性有什么用。

标签: javascript console panel setattribute


【解决方案1】:

document.querySelectorAll 返回一个静态的nodelist,所以需要迭代这个集合来访问元素。然后setAttribute 可以用来设置一个属性

var getAllLI = document.querySelectorAll('.demoClass');
getAllLI.forEach(function(item, index) {
  item.setAttribute('value', index)
})
<input class="demoClass">
<input class="demoClass">
<input class="demoClass">
<input class="demoClass">

【讨论】:

  • 谢谢,非常感谢,我的问题得到了答案