javascript - 可以在 getElementById 中使用通配符吗?

标签 javascript html

我有以下代码行:

document.getElementById("question_*").setAttribute("disabled", "false");

我想为元素 ID 使用通配符形式。该脚本由许多不同的按钮运行和使用,它们都有 question_something 的 ID - 是否有可能使此 setAttribute 为各种 ID 启用按钮?

<button id="question_1a" onClick="nextQuestion(this.id)" disabled>Next question</button>

编辑:

我已按照建议切换到类名。按钮现在是:

<button id="question_1a" class="nextButton" disabled>Next question</button>

我添加了以下行以使其不被禁用:

var elems = document.getElementsByClassName('nextButton').setAttribute("disabled", "false");

但我得到:Uncaught TypeError: Object # has no method 'setAttribute'

最佳答案

document.getElementById() 不能使用通配符,可以,但是document.querySelectorAll():

var elems = document.querySelectorAll('button[id^="question_"]');

当然,这需要一个相对最新的浏览器;另一方面,使用类名(例如 question)来关联这些元素将允许您使用:

var elems = document.getElementsByClassName('question');

或者:

var elems = document.querySelectorAll('button.question');

I tried doing this: var elems = document.getElementsByClassName('nextButton').setAttribute("disabled", "false"); - but I get: Uncaught TypeError: Object # has no method 'setAttribute'

那是因为您不能一次修改 NodeList 的所有属性,但是,您可以使用 for (){...} 循环或类似的方法来执行此操作:

使用 for(){...}:

var elems = document.getElementsByClassName('question');
for (var i = 0, len = elems.length; i < len; i++){
    elems[i].disabled = false; // to make them all enabled
}

JS Fiddle demo .

或者使用 forEach(最新的浏览器):

var elems = document.getElementsByClassName('question');
[].forEach.call(elems, function(a){
    a.disabled = false; // will make all elements enabled
});

JS Fiddle demo .

引用资料:

关于javascript - 可以在 getElementById 中使用通配符吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22442808/

相关文章:

javascript - Polymer 2.5.0 - dom-repeat 未更新

javascript - 在表单上隐藏成功和错误消息

jquery - jQuery 加载中不显示重音

javascript - 如何在 Angular 7 中使用 JavaScript 代码?

javascript - 如何在特定数字的每两个偶数位之间插入破折号

javascript - 一种在 iOS (iPhone, iPad) 上跳过崩溃的方法

javascript - 在 Bootstrap 中重新定位导航栏上的元素折叠

javascript - RequireJS 的异步特性

javascript - 自动转到在 React Virtual Dom 中创建的 div 元素

javascript - 为动态创建的控件触发事件