title: How can I know the id of a JSF component so I can use in Javascript
body: <p><strong>Problem:</strong> Sometimes you will want to access a component from javascript with
  <code>getElementById</code>, but id's are generated dynamically in JSF, so you
  need a method of getting an objects id.  I answer below on how you can do this.</p>
  
  <hr>
  
  <p><strong>Original Question:</strong>
  I want to use some code like below.  How can I reference the inputText JSF component in my Javascript?</p>
  
  <pre><code>&lt;html xmlns="http://www.w3.org/1999/xhtml"
        xmlns:h="http://java.sun.com/jsf/html"
        xmlns:f="http://java.sun.com/jsf/core"&gt;
      &lt;head&gt;
         &lt;title&gt;Input Name Page&lt;/title&gt;
          &lt;script type="javascript" &gt;
            function myFunc() {
              // how can I get the contents of the inputText component below          
              alert("Your email address is: " + document.getElementById("emailAddress").value);
            }
         &lt;/script&gt;
      &lt;/head&gt;
      &lt;h:body&gt;
          &lt;f:view&gt;
              &lt;h:form&gt;
                  Please enter your email address:&lt;br/&gt;
                  &lt;h:inputText id="emailAddresses" value="#{emailAddresses.emailAddressesStr}"/&gt;
                  &lt;h:commandButton onclick="myFunc()" action="results" value="Next"/&gt;
              &lt;/h:form&gt;
          &lt;/f:view&gt;
      &lt;/h:body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <hr>
  
  <p><strong>Update</strong>: this post <a href="http://illegalargumentexception.blogspot.com/2009/10/jsf-working-with-component-identifiers.html#clientidjsf2_0" rel="noreferrer">Client Identifiers in JSF2.0</a> discusses using a technique like:</p>
  
  <pre><code>&lt;script type="javascript" &gt;
    function myFunc() {
      alert("Your email address is: " + document.getElementById("#{myInptTxtId.clientId}").value);
    }
  &lt;/script&gt;
  
  &lt;h:inputText id="myInptTxtId" value="backingBean.emailAddress"/&gt;
  &lt;h:commandButton onclick="myFunc()" action="results" value="Next"/&gt;
  </code></pre>
  
  <p>Suggesting that the attribute <code>id</code> on the <code>inputText</code> component
  creates an object that can be accessed with EL using <code>#{myInptTxtId}</code>,
  in the above example.  The article goes on to state that JSF 2.0 adds
  the zero-argument <code>getClientId()</code> method to the <code>UIComponent</code> class.
  Thereby allowing the <code>#{myInptTxtId.clientId}</code> construct suggested
  above to get the actual generated id of the component.</p>
  
  <p>Though in my tests this doesn't work.  Can anyone else confirm/deny.
  The answers suggested below suffer from drawback that the above
  technique doesn't.  So it would be good to know if the above technique
  actually works.</p>