I'm trying to figure out a way to click this with JavaScript's .click()
<input type="button" class="button" value="Test">
Is there a way to do that wit开发者_JAVA技巧h the given attributes or do I need to add more (Id or Name) so I can use getElementby
?
you could do it with getElementsByTagName("input") and look for items with an attribute type of button-- but you're better off getting it with an id attribute.
Going off the top of my head:
var buttons = document.getElementsByTagName('input');
for (var i = 0; i < buttons.length; i++) {
if ((i.type == 'button') && (i.className == 'button') && (i.value == 'Test')) {
i.click();
break;
}
}
It'd definitely be easier to put an ID onto the button, so you can simply have/do:
<input id="mybutton" class=... ...>
document.getElementById('mybutton').click();
You'll save yourself a lot of hastle if you add an id
attribute to your HTML.
Then you can simply do:
document.getElementById('mybutton').click();
and with a null check:
var element = document.getElementById('mybutton');
if(element != null)
{
element.click();
}
I think the easiest way would be to add an id. One alternative would be to get all the DOM elements, then search through them until you found one with the exact values, but that's a lot of unnecessary work.
You can surely retrieve the element by using existing attributes but this depends on which other buttons you have in your form. Having a specified id
is always a good idea in these situations.
Even using jQuery with $("#yourid").click()
is always a good idea..
`<input type="button" class="button" value="Test" id="btnTest">`
`<input type="button" class="button" value="Test" id="clickTest" onclick="myClick()">`
function myClick()
{
btnTest.click();
}
精彩评论