SalesforceBlue

Feel the rhythm of Salesforce

Aura

Locating the DOM In Aura Component

Before learning about locating DOM in the Aura Component, let’s take a quick tour of HTML DOM and its significance in web app development.

Whenever a web page is loaded, the browser constructs the DOM (Document Object Model) for it.

Below is an illustration of the HTML DOM:

The HTML DOM is constructed as a tree of objects.

You can consider it as a tree having the root as the Document node which grows all the way to the last element node present in the hierarchy of the elements.

Javascript can access and change all the elements present in the DOM generated by the browser.

This allows us to write dynamic web pages which can be altered using Javascript.

If you have to locate the DOM in an HTML web page, below is the snippet for it:

var obj = document.getElementById("elementId");

The above block returns an object which represents an HTML element for the given element Id.

This object can be used for any manipulations in the DOM or getting element properties by Javascript.

Using Component.find() To Locate The DOM In Aura Components:

You can use component.find(“elementAuraId”) function to locate the DOM.

An aura:id must be assigned to the DOM element. If there are multiple elements with the same ID, an array will be returned.

Let’s see them in action below:

We will be modifying the code in MyAwesomeAuraComponent which we have created earlier.

<aura:component>
    <aura:attribute name="welcome" type="String" default="Hey, Welcome to SalesforceBlue :)" />

    <lightning:card title="AwesomeAuraComponent">
        <aura:set attribute="actions">
            <lightning:button label="Click Me!" onclick="{!c.greetings}"/>
        </aura:set>

        <p class="slds-p-horizontal_small" aura:id="p1">
            <p>{!v.welcome}</p>
        </p>
    </lightning:card>
</aura:component>	

({
    greetings : function(component, event, helper) {
       var obj = component.find("p1").getElement();
       console.log('Inner Text > ' + obj.innerText);
    }
})

Let’s preview the component in the aura app and observe the logs. You will see similar to the below screenshot.


Thank you for visiting SalesforceBlue.com
If you have any queries feel free to write down a comment below 🙂


Leave a Reply

Your email address will not be published. Required fields are marked *