Posted in Dojo Cookies
jsId, dijit.byId() and dojo.byId()
A common question new users of dojo have is what is the difference between jsId, dijit.byId() and dojo.byId().
Consider the following simple ContentPane widget which has an id property (standard html attribute for any tag) and a jsId attribute (dojo specific id attribute explained below):
<div id="myDivId" dojoType="dijit.layout.ContentPane" jsId="myJSId"> Hello Everyone! </div>
dojo.byId()
dojo.byId() is no different than the often used document.getElementById() to access the DOM node for the div tag - simply pass in the tag’s id attribute value.
For example:
dojo.byId("myDivId").style.height = '300px';
This would set a style height property.
dijit.byId()
dijit.byId() is a little different - first off it only works on parsed dijits either declared in markup with a dojoType attribute or programatically. The same id attribute is used as a paramater, but what is returned in this case is an object that was created by the dojo widget system when the markup is parsed and transformed into a dijit. This allows you to change dojo-specific attributes for the widget or call methods defined in the class the dijit corresponds to (in this case, we can call methods of the ContentPane class). For Example, we can set the content of the ContentPane via setContent().
dijit.byId("myDivId").setContent("Hello World!");
You could also change the style like we did with dojo.byId() above using the domNode property of the ContentPane (actually - domNode is defined higher up the inheritance tree so every dijit has a domNode property - very convenient!) This example also saves the results of dijit.byId() into a local variable.
myContentPane = dijit.byId("myDivId"); myContentPane.domNode.style.height = '300px'; myContentPane.setContent("Hello World!");
jsId
jsId saves you one more step in working with widgets by automatically creating a global javascript variable for you (the dojo parser does this). This variable contains the same object as returned by dijit.byId(). Whatever value you give to the jsId attribute becomes the name of the global variable so watch out for reserved words or having two widgets with the same jsId! Since my Content Pane has a jsId attribute value of myJSId I could simplify the above code a little by removing the dijit.byId() and using my jsId attribute as the variable name:
myJSId.domNode.style.height = '300px'; myJSId.setContent("Hello World!");
jsId is not a required attribute, it is there as a convenience.
Additional information:
- Dojotoolkit.org - dojo.byId and dijit.byId
Tags: dojo.byId()