If you use Javascript in Visualforce page, you may find out that it is more time consuming to get elements from page. Visualforce tags have some lifecycle during rendering page. Lets create simple page:

Here is the final HTML source code of written commandButton

As you can see, id is j_id0:j_id1:theButton not just theButton. Other identificators are added by Visualforce during rendering to make unique ID + store some hierarchy.

If we want to work with this button in Javascript, we have 3 options how to get this element.


The first : use Visualforce component

We can use Visualforce component value, which stores all calculated ID. For example

My advise is to use this after commandButton is rendered, so somewhere in the end of the page.


The second : use jQuery (my recommendation)

In this solution I use jQuery with special selector, which selects ID ending with specific string.

I love jQuery, so I prefer this solution, because I do not have to care if Id in $Component already exists, so I can put this piece of code everywhere and it can directly work with call jQuery functions.

You can change selector and get for example all buttons from page:

This code returns all buttons, because all Salesforce buttons have style class btn.


The third : Select element by class name

This solution is the longest, but it also works. At first you need to add style Class (CSS class) to button. Update your test page by adding styleClass = “buttonClass” :

then put this javascript function into page

which defines function getElementsByClassName. This function returns element based on its class name (it is similar to getElementsById, but it works for style classes). You can find many more similar function, which return element based on class name, and you can use it instead of this, but I tested this and it works perfect.

Now you can select element like in the first solution: