AS3 Naming and Retrieving Elements Dynamically

Recently ran across this problem in Actionscript 3 with dynamically naming and retrieving child elements. Created a loop to name sprites and add using the name property and addChild method:

for ( var i:int = 1;  i <= 3;  i++ ) {
	var bkgd:Sprite = new Sprite (); = "bkgd" +i;
	addChild ( bkgd );


Now these sprites are accessible via getChildByName and are retrieved as DisplayObject by default. But when retrieved as DisplayObject, you can not add children via addChild method. The trick is to cast the DisplayObject as a Sprite:

var addBkgd:Sprite = Sprite ( this.getChildByName( "bkgd" +layerNum ) );
addBkgd.addChild ( layerSprite );