[SalesForce] Display error or warning message without ApexPages using Global Component

I have a simple form , which has a output panel and pageMessage inside it .

<apex:form>
        <apex:outputPanel id="errorPanel">
            <apex:message id="msg" />
        </apex:outputPanel>
</apex:form>

I have visual force remoting function which returns a json result object containing message, errorCode if there is error, and other key/value parameters. Now once this json object is returned, there is a call back function which must display the error message on the screen if there is an error. How can i display the error message using the global $Component syntax? I am trying to set the title of the message as shown below, but I get this error:
"Cannot set property 'title' of null" .

function handleresult (result,event){
if(!result.success){
            //display error message 
            var element =  document.getElementById('{!$Component.errorPanel.msg}');
            element.title = result.message;

            return;
} 

Please help me out solving this issue??

Best Answer

Since your <apex:message /> component is nested one, you might need to use more complete path specifier as described in the documentation here.

So try below VF code

<apex:form id="myForm">
        <apex:outputPanel id="errorPanel">
            <apex:message id="msg" />
        </apex:outputPanel>
</apex:form>

And access it in your JS function as below.

var element =  document.getElementById('{!$Component.myForm.errorPanel.msg}');

Also note that if your form component has any parent components you might need to introduce ids for them as well and use that full path in your JS function.