[SalesForce] In current SF release lightning component.find(…).getElement is not working

In current SF release lightning component.find(…).getElement is not working. I understand this due to Locker service which is blocking DOM elements from getting accessed.

So is there any better way we can access the attributes of elements using other lightning methods ?

Best Answer

Here is a working example .app of what I think you are saying is not working for you (NOTE TO MODERATORS: I did not use a comment because they do not provide enough formatting capabilities to handle code etc).

@nevrekar_amey Please provide something similar that showcases the error case you are seeing.

<aura:application>
    <div aura:id="divID" class="blue">Hi</div>
    <lightning:button label="Remove Class" onclick="{!c.removeClass}"/>
</aura:application>

controller:

({
    removeClass : function(component, event, helper) {
        helper.removeClassHelperMethod(component);
    }
})

helper:

({
    removeClassHelperMethod : function(component) {
        var divElement = component.find('divID').getElement(); 
        $A.util.removeClass(divElement, 'blue'); 
    }
})

css:

.THIS.blue {
    background-color: blue;
}

Or an even better approach that does not run the risk of colliding with Lightning's stewardship of the DOM elements its managing on your behalf:

<aura:application>
    <aura:attribute name="class" type="String" default="blue" access="private"/>
    <div aura:id="divID" class="{!v.class}">Hi</div>
    <lightning:button label="Toggle Class" onclick="{!c.toggle}"/>
</aura:application>

({
    toggle : function(component, event, helper) {
        component.set("v.class", component.get("v.class") === "" ? "blue" : "");
    }
})

Even better - this approach is also guaranteed to work in your init scenario too!

<aura:application>
    <aura:attribute name="class" type="String" default="blue" access="private"/>
    <aura:handler name="init" value="{!this}" action="{!c.init}"/>

    <div aura:id="divID" class="{!v.class}">Hi</div>
    <lightning:button label="Toggle Class" onclick="{!c.toggle}"/>
</aura:application>

({
    init : function(component, event, helper) {
        component.set("v.class", "green");
    },

    toggle : function(component, event, helper) {
        component.set("v.class", component.get("v.class") === "" ? "blue" : "");
    }
})

.THIS.blue {
    background-color: blue;
}

.THIS.green {
    background-color: green;
}