Using $Component to Reference Components from JavaScript

Use the $Component global variable to simplify referencing the DOM ID that is generated for a Visualforce component, and reduce some of the dependency on the overall page structure.

Every Visualforce tag has an id attribute. The id attribute for a tag can be used by another tag to bind the two tags together. For example, the <apex:outputLabel> tag’s for attribute can be used with the <apex:inputField> tag’s id attribute. The reRender and status attributes on <apex:actionFunction>, <apex:actionSupport>, and other action-oriented components also use the value of the id attribute from other components.

In addition to being used to bind Visualforce components together, this ID is used to form part of the document object model (DOM) ID for the component when the page is rendered.

To refer to a Visualforce component in JavaScript or another Web-enabled language, you must specify a value for the id attribute for that component. A DOM ID is constructed from a combination of the id attribute of the component and the id attributes of all components that contain the element.

Component Access Example

The following example uses the DOM ID for an <apex:outputPanel> tag. The page contains two panels: the first holds a checkbox that fires a DOM event, and the second contains some text that’s changed in response to the event.

The top of the page includes JavaScript contained within the <script> HTML tag. It takes as arguments the element that triggered the event (input) and the DOM ID (textid) of the target panel containing the text to be affected.

<apex:page id="thePage">
    <!-- A simple function for changing the font. -->
    <script> function changeFont(input, textid) { if(input.checked) { document.getElementById(textid).style.fontWeight = "bold"; } else { document.getElementById(textid).style.fontWeight = "normal"; } } </script> <!-- This outputPanel calls the function, passing in the checkbox itself, and the DOM ID of the target component. -->
    <apex:outputPanel layout="block"> <label for="checkbox">Click this box to change text font:</label> <input id="checkbox" type="checkbox"
            onclick="changeFont(this,'{!$Component.thePanel}');"/> </apex:outputPanel> <!-- This outputPanel is the target, and contains text that will be changed. -->
    <apex:outputPanel id="thePanel" layout="block"> Change my font weight! </apex:outputPanel> </apex:page>

The {!$Component.thePanel} expression is used to obtain the DOM ID of the HTML element generated by the <apex:outputPanel id="thePanel"> component.

© Copyright 2000–2014 salesforce.com, inc. All rights reserved.
Various trademarks held by their respective owners.