Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Javascript - How to Click a Submit Button that has No ID, Value or Name

Tags:

javascript

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.

like image 967
Learning Avatar asked Dec 16 '22 11:12

Learning


1 Answers

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();
like image 101
Christofer Eliasson Avatar answered Apr 05 '23 23:04

Christofer Eliasson