Is there a way to get all the button tag and their types on a particular page using javascript?
Is there a way to get all the button tag and their types on a particular page using javascript?
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)
var buttons = document.querySelectorAll(".classname").length;
for (var i = 0; i < buttons; i++) {
document.querySelectorAll(".classname")[i].addEventListener("click", function () {
alert("clicked!");
});
}