3

How do access all of the children of a DisplayObject using code? (I'm looking for something like movieclip.children)

I'm using this in two cases:

1) To loop through and reposition all of the children of an enclosing MovieClip.

Or

2) To loop through and delete all of the children of a MovieClip

Also, this is a Flash CS5 project.

shanethehat
  • 15,460
  • 11
  • 57
  • 87
Moshe
  • 57,511
  • 78
  • 272
  • 425

3 Answers3

6

This loop will touch every child inside movieclip foo. I'm not sure what you're going to do to them, but you can run whatever methods you need inside the loop.

for (var i:uint=0; i<foo.numChildren;i++){
    foo.getChildAt(i).whateverMethodYouNeed();
}
John
  • 3,904
  • 7
  • 31
  • 43
  • Note that there is no array-style accessor like `children[n]`. You always use the `get` methods to access children one-by-one. – fenomas Nov 16 '10 at 00:17
  • Bad answer for two reasons: loop is slower then var i:int = numChildren; while(i-- > 0) getChildAt(i), DisplayObject has no method "whateverMethodYouNeed" – average dev Jan 04 '12 at 13:14
0

Is your object just a display object? If it is an UIComponent, you could use getChildAt() and getChildByName() along with the numChildren property to loop over them. Is this part of a flex project or an actionscript only project?

A DisplayObject itself does not have the mechanisms to describe its children. The lowest level type that knows about children is the DisplayObjectContainer. You may have to convert the object into at least a DisplayObjectContainer to be able to do what you want. I would go with an UIComponent though if you have the flex framework to work with.

DisplayObject

DisplayObjectContainer

UIComponent

Ryan Guill
  • 13,558
  • 4
  • 37
  • 48
0

If you need to access all the children, inclusive of a child's children, you can try this:

    function doWhatever( mc:DisplayOjectContainer ):void
    {
          if( mc.numChildren > 0 )
             for( var i:int ; i < mc.numChildren ; ++i )
             {
                 //if you need to reposition
                //set the points properties here
                var point:Point = new Point( _x , _y );
                setPosition ( mc.getChildAt(i ) , point );

                //if you need to remove all children
                //do it recursively
                //remove( mc , mc.getChildAt( i );
             }
    }

    function setPosition(mc:DisplayObject , point:Point ):void
    {
        mc.x = point.x ;
        mc.y = point.y;
    }

    function remove(container:DisplayObjectContainer , child:DisplayObject ):void
    {
         //this will remove all children before being removed
         if( child is DisplayObjectContainer )
         {
             var doc:DisplayObjectContainer = child as DisplayObjectContainer;
             doWhatever( doc );
         }

         container.removeChild( child );
         child = null;
    }
PatrickS
  • 9,539
  • 2
  • 27
  • 31