0

I'm trying to modify the DOM and access a lightning component attribute at the same method.

I tried using init handler but I can't access the DOM there.

I tried using render handler but I can't access the attribute there.

Is there a method I can access both ? I need it to run in the beginning of the component lifecycle (like init or render)

init : function(component, event, helper){

    var pathItems = document.getElementsByClassName("slds-path__item");
    console.log('pathItems: ' + pathItems.length);
    for (var i=0; i<pathItems.length; i++){
        var item = pathItems[i];
        var status = item.getAttribute("data-value");
        var commission = component.get("v.commission");

        //first set incomplete
        $A.util.addClass(item, 'slds-is-incomplete');
        console.log('status: ' + commission.Status__c);
        if (status == commission.Status__c){
            $A.util.removeClass(item, 'slds-is-incomplete');
            $A.util.addClass(item, 'slds-is-active');
            $A.util.addClass(item, 'slds-is-current');

            if (status == 'Pending Final Approval'){
                $A.util.removeClass(pathItems[i-1], 'slds-is-incomplete');
                $A.util.addClass(pathItems[i-1], 'slds-is-complete');
            }
            else if (status == 'Approved For Payment'){
                $A.util.removeClass(pathItems[i-1], 'slds-is-incomplete');
                $A.util.addClass(pathItems[i-1], 'slds-is-complete');
                $A.util.removeClass(pathItems[i-2], 'slds-is-incomplete');
                $A.util.addClass(pathItems[i-2], 'slds-is-complete');
            }
        }
    }
}
0

You can't access the DOM until after it has been rendered initially. I actually implemented path using only expressions, no direct class manipulation required. That said, for DOM manipulation, use afterRender instead. There's actually several examples of path components already built you can look at, such as strike_path. Also note that render passes in all the elements that will be created, so you can manipulate the classes of those elements before being added to the DOM, which would give better performance.

  • Thanks for the response, when I use afterRender, I get this error: "Failed to initialize a component [Cannot read property 'g' of undefined]". I don't know how to solve this. – osos9 Jan 2 at 9:49
  • @osos9 We'd need to see the afterRender method you wrote to figure out what's up, but again, I'd suggest not using a custom renderer, it's simply not necessary. – sfdcfox Jan 2 at 9:51
  • I paste the method in the question (called init). What do you mean by "custom renderer" ? – osos9 Jan 2 at 10:56
  • @osos9 See the link for afterRender in this answer. It talks about custom renderers. – sfdcfox Jan 2 at 15:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.