开发者

Get all the button tag types

开发者 https://www.devze.com 2023-03-17 04:31 出处:网络
Is there a way to get开发者_开发问答 all the button tag and their types on a particular page using javascript?Have this code either in the load event of the document, or in the bottom of the HTML:

Is there a way to get开发者_开发问答 all the button tag and their types on a particular page using javascript?


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
    // ...
}


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)


var buttons = document.querySelectorAll(".classname").length;
for (var i = 0; i < buttons; i++) {
  document.querySelectorAll(".classname")[i].addEventListener("click", function () {
    alert("clicked!");
  });
}
0

精彩评论

暂无评论...
验证码 换一张
取 消