I have the following line of code:
document.getElementById("question_*").setAttribute("disabled", "false");
I want to use a form of wildcard for the element ID. The script is run and used by lots of different buttons, they all have ID's of question_something
- is it possible to make this setAttribute
to make the button enabled for various ID's?
<button id="question_1a" onClick="nextQuestion(this.id)" disabled>Next question</button>
EDIT:
I've switched to a classname as suggested. Buttons now are:
<button id="question_1a" class="nextButton" disabled>Next question</button>
I've added the following line to make this not disabled:
var elems = document.getElementsByClassName('nextButton').setAttribute("disabled", "false");
But I get: Uncaught TypeError: Object # has no method 'setAttribute'
You can't use wildcards with document.getElementById()
, you can, however, with document.querySelectorAll()
:
var elems = document.querySelectorAll('button[id^="question_"]');
This, of course, requires a relatively up to date browser; on the other hand using a class-name (for example question
) to associate those elements would allow you to use:
var elems = document.getElementsByClassName('question');
Or:
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'
That's because you can't modify the properties of a NodeList all at once, you can, however, use a for (){...}
loop, or similar to do so:
Using 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.
Or using forEach (up to date browsers):
var elems = document.getElementsByClassName('question');
[].forEach.call(elems, function(a){
a.disabled = false; // will make all elements enabled
});
JS Fiddle demo.
References:
Array.prototype.forEach()
.document.getElementById()
.document.getElementsByClassName()
.document.querySelector()
compatibility.document.querySelectorAll()
compatibility.Function.prototype.call()
.for
loop.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With