How can I use javascript to "click" a button that has no id, value, class or name?
The relevant code for the button is:
<div class="classname anotherclassname" title="">
<div>
<button type="submit"><i class="anotherclass anotherclassname"></i>ImAButton</button>
</div>
</div>
I'd give an example of what I have so far, as I know that is simply good etiquette here on stackoverflow, but I don't even know where to start. The only way I presently know how to use javascript to click a button is using this:
document.getElementById("myButtonId").click();
And that doesn't apply here.
How can I use javascript to "click" a button that has no id, value, class or name?
The relevant code for the button is:
<div class="classname anotherclassname" title="">
<div>
<button type="submit"><i class="anotherclass anotherclassname"></i>ImAButton</button>
</div>
</div>
I'd give an example of what I have so far, as I know that is simply good etiquette here on stackoverflow, but I don't even know where to start. The only way I presently know how to use javascript to click a button is using this:
document.getElementById("myButtonId").click();
And that doesn't apply here.
Share Improve this question asked Apr 10, 2013 at 11:52 LearningLearning 1,19110 gold badges20 silver badges30 bronze badges 9- 1 Is there only the one submit button on the DOM ? – asawyer Commented Apr 10, 2013 at 11:53
- what is the reason for no name and id – PSR Commented Apr 10, 2013 at 11:54
-
If it is the only submit-button on the page, you could select it with
document.querySelectorAll("button[type='submit'])
– Christofer Eliasson Commented Apr 10, 2013 at 11:54 - <button type="submit" onclick="yourFunction()"> create a functionin your script then – Deepanshu Goyal Commented Apr 10, 2013 at 11:56
- 1 I would say why click the button? Submit the form – epascarello Commented Apr 10, 2013 at 12:16
2 Answers
Reset to default 9If you are okay with only supporting modern browsers and IE8 and above, then you could use document.querySelectorAll
to select the element. Given that the button is the only button of type submit on the page, you could do:
document.querySelectorAll("button[type='submit']")[0].click();
querySelectorAll takes any valid CSS-selector (IE8 only support CSS2 selectors). So if you need to make the selection more specific, you could just make the selector more specific as you would with any CSS-selector. Something like this for example:
document.querySelectorAll(".classname button[type='submit'"])[0].click();
You can get all button on page using
buttons = document.getElementsByTagName('button');
document.getElementsByTagName('button')[0].click();
may fire a click on the first button.