[SalesForce] Lightning/Aura Components: component.find().getElement never accessible

What are the actions that might destructively interfere with the lightning app's lifecycle? Is a breakpoint\debugger statement one of such?

For example there is a case that I happen to meet regularly after Winter 17 release (everything below is performed with Locker Service on, switching it off is not an option). Assume we have some component with an init event handler and "select" element:

...
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<select aura:id="select-element" class="slds-select" onchange="{!c.handleSelect}"></select>

And here's an "init" handler:

doInit : function(component, event, helper) {
    // do smth
    debugger; // this can be a debugger statement or manually put browser's breakpoint
}

If we happen to have an open console and we catch this breakpoint (immediately resuming it, or not) – in any time later there's no chance to get access to element:

...
component.find("select-element").getElement;

Same happens with div element's, maybe with others.

With absolutely same component's layout and js-controller\helper etc. but with browser's console closed (hence the breakpoint isn't caught) getElement function is there and some code that depends on it will execute successfully.

EDIT:
the DOM element is there already (meaning if I use afterRender or some custom button to get a breakpoint far after the init() was executed), I can see it and interact with it – but the getElement function nevertheless is unreachable at that same moment.

Best Answer

You are hitting a timing issue with init that is by design - you should not use component.getElement() in init because elements are not reliably available in init handlers - you'll want to look into using a custom renderer afterRender method which gets called at a point where you are guaranteed to have actual DOM elements available and was designed for exactly this ind of scenario.

https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/js_renderers.htm