DOM Access Containment

A component can only traverse the DOM and access elements created by a component in the same namespace. This behavior prevents the anti-pattern of reaching into DOM elements owned by components in another namespace.
Note

Note

It’s an anti-pattern for any component to “reach into” another component, regardless of namespace. LockerService only prevents cross-namespace access. Your good judgment should prevent cross-component access within your own namespace as it makes components tightly coupled and more likely to break.

Let’s look at a sample component that demonstrates DOM containment.

<!--c:domLocker-->
<aura:component>
    <div id="myDiv" aura:id="div1">
        <p>See how LockerService restricts DOM access</p>
    </div>
    <lightning:button name="myButton" label="Peek in DOM"
                aura:id="button1" onclick="{!c.peekInDom}"/>
</aura:component>

The c:domLocker component creates a <div> element and a <lightning:button> component.

Here’s the client-side controller that peeks around in the DOM.

({ /* domLockerController.js */
    peekInDom : function(cmp, event, helper) {
        console.log("cmp.getElements(): ", cmp.getElements());
        // access the DOM in c:domLocker
        console.log("div1: ", cmp.find("div1").getElement());
        console.log("button1: ", cmp.find("button1"));
        console.log("button name: ", event.getSource().get("v.name"));

        // returns an error
        //console.log("button1 element: ", cmp.find("button1").getElement());
    }
})

Valid DOM Access

The following methods are valid DOM access because the elements are created by c:domLocker.

cmp.getElements()
Returns the elements in the DOM rendered by the component.
cmp.find()
Returns the div and button components, identified by their aura:id attributes.
cmp.find("div1").getElement()
Returns the DOM element for the div as c:domLocker created the div.
event.getSource().get("v.name")
Returns the name of the button that dispatched the event; in this case, myButton.

Invalid DOM Access

You can’t use cmp.find("button1").getElement() to access the DOM element created by <lightning:button>. LockerService doesn’t allow c:domLocker to access the DOM for <lightning:button> because the button is in the lightning namespace and c:domLocker is in the c namespace.

If you uncomment the code for cmp.find("button1").getElement(), you’ll see an error:

c:domLocker$controller$peekInDom [cmp.find(...).getElement is not a function]