Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
93
rated 0 times [  96] [ 3]  / answers: 1 / hits: 22696  / 11 Years ago, wed, april 10, 2013, 12:00:00

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.


More From » javascript

 Answers
10

If 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();

[#78995] Tuesday, April 9, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
parisc

Total Points: 438
Total Questions: 119
Total Answers: 119

Location: Turkmenistan
Member since Sat, Apr 16, 2022
2 Years ago
;