The Flex code

We start by adding the following two helper functions for locating the Flex components by id in a file named testAPI.as.

You can copy this code from this page or download the source file here.

import mx.core.UIComponent;

/**
 * Find a UIComponent using its id attribute, wherever it is in the application
 * @param  id  id attribute of the UIComponent to return
 * @return     the UIComponent corresponding to the id, or null if not found
 */
private function getElementById(id:String):UIComponent {
  return getElementByIdRecursive(id, this);
}

private function getElementByIdRecursive(id:String, root:UIComponent):UIComponent {
  for(var i:int = 0; i<root.numChildren; i++) {
    try {
      var child:UIComponent = UIComponent(root.getChildAt(i));
      if(child.id == id) return child;
      var node:UIComponent = getElementByIdRecursive(id, child);
      if(node!=null) return node;
    }
    catch(e:Error) {
    }
  }
  return null;
}