I am trying to get an html element through it's class name within in a lightning component controller.
Something that will work like document.getElementsByClassName
component.find("aura:id")
won't help me – I need to get an existing html element, not something that I am generating.
Is there any option?
Thanks
UPDATE:
I use this component from within a lightning component quick action on the contact object:
Markup:
<aura:component implements="force:lightningQuickAction,force:hasRecordId,flexipage:availableForAllPageTypes">
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<div class="myTest" title="testTitle" >
<div class="test2" >
test
<a href="test" >test</a>
</div>
</div>
</aura:component>
Controller:
({
doInit : function(component, event, helper) {
var elements = document.getElementsByClassName("myTest");
console.log("elements.length: " + elements.length);
for (var i=0; i<elements.length; i++) {
console.log(elements[i].innerHTML);
}
}
})
And I get an empty array – elements.length is 0.
What can be the problem?
Best Answer
init
handler is called long before DOM is rendered in the view by the component. The appropriate place to access DOM, is in Renderer.Add
afterRender
method which in turn gets called once the DOM rendering is done: