Get all the button tag types
I tried with the original answer with no success, so i use this :
var elements = document.querySelectorAll("input[type=button]");
Example:
var elements = document.querySelectorAll("input[type=button]");
for(var i = 0, len = elements.length; i < len; i++) {
console.log("Button: " + elements[i].id);
}
<input type="button" id="alfa" value="alfa">
<input type="button" id="beta" value="beta">
<input type="button" id="gamma" value="gamma">
<input type="button" id="omega" value="omega">
As the answer from @jorgesys points out, use:
document.getElementsByTagName("button");
That returns an HTMLCollection
instance. In modern JavaScript you can convert to an array and use map
:
Array.from(document.getElementsByTagName("button"))
.map(b => b.getAttribute('type'))
That will return an array like ["submit", "submit", null, null, ...]"
I recently needed to disable all buttons, which could be done using forEach
:
Array.from(document.getElementsByTagName("button"))
.forEach(b => b.disabled = true)
Or to avoid the temporary array (which probably isn't something you should worry about), you could create this:
function forEachButton(func) {
let elements = document.getElementsByTagName("button");
for(let i = 0, len = elements.length; i < len; i++) {
func(elements[i])
}
}
Then disable all buttons with:
forEachButton(b => b.disabled = true)
Have this code either in the load event of the document, or in the bottom of the HTML:
var buttons = document.getElementsByTagName('button');
for (let i = 0; i < buttons.length; i++) {
let button = buttons[i];
let type = button.getAttribute('type') || 'submit'; // Submit is the default
// ...
}