Tuesday 13 August 2013

Get Visual Force Page Element By document.getElementById In Javascript


Some time we try to get element of apex page (Element created by apex tag)  in javascript by their Id.
But we know element which is created apex tag have their on own prefix eg:

<apex:inputText value="{!Test}" id="TEXTELEMENT" />

We know when ever we try to get the html element in java script we will write :

var e = getElementById('TEXTELEMENT') ;

but we get error as apex visual force add the parent element id as suffix in the "TEXTELEMENT" .
eg:-

jdi:ooa TEXTELEMENT

So there is a small function which is not written by me but when I try to find I got this which I am sharing with all us.

  function getApexElementByID(tagname, eid) {
            var tags = document.getElementsByTagName(tagname); //get a bunch of tags.
            var regex = new RegExp(":" + eid + "$");
            for (var i=0; i < tags.length; i++) {
                if (tags[i].getAttribute("id") != null) {
                    var idVal = tags[i].getAttribute("id");
                    var pos = idVal.search(regex);
                    if (pos != -1) return tags[i];
                }
            }
            return null;
        }
This function return that element those id we will pass as a second parameter. The first parameter is for element type.

eg : var myElement  = getApexElementByID('input','TEXTELEMENT ');


I think you will like it.