Newer Version Available

This content describes an older version of this product. View Latest

Modifying the DOM

The Document Object Model (DOM) is the language-independent model for representing and interacting with objects in HTML and XML documents. It's important to know how to modify the DOM safely so that the framework's rendering service doesn't stomp on your changes and give you unexpected results.

The framework’s rendering service takes in-memory component state and creates and manages the DOM elements owned by the component. The framework automatically renders your components so you don't have to know anything more about rendering unless you need to customize the default rendering behavior for a component.

There are a few supported ways to modify the DOM.

DOM Elements Managed by the Lightning Component Framework

The framework creates and manages the DOM elements owned by a component. If you want to modify these DOM elements created by the framework, modify the DOM elements in the component's renderer. Otherwise, the framework will override your changes when the component is rerendered.

For example, if you modify DOM elements directly from a client-side controller, the changes may be overwritten when the components are rendered. Instead, update the component's attributes and let the framework's rendering service take care of the DOM updates.

You don't normally have to write a custom renderer, but it’s useful if you need to interact with the DOM tree after the framework’s rendering service has inserted DOM elements. If you want to customize rendering behavior and you can’t do it in markup or by using the init event, create a client-side renderer.

In a renderer, modify the DOM that belongs to the current component only. Never break component encapsulation by reaching into another component and changing its DOM elements, even if you are reaching in from the parent component.

There are often better alternatives to creating a custom renderer. Consider using an expression in the markup instead of setting a DOM element directly.

You can modify CSS classes for a component outside a renderer by using the $A.util.addClass(), $A.util.removeClass(), and $A.util.toggleClass() methods.

You can read from the DOM outside a renderer.

DOM Elements Managed by External Libraries

You can use different libraries, such as a charting library, to create and manage DOM elements. You don't have to modify these DOM elements within a renderer. A renderer is only used to customize DOM elements created and managed by the Lightning Component framework.

To use external libraries, use <ltng:require>. This tag orchestrates the loading of your library of choice with the rendering cycle of the Lightning Component framework to ensure that everything works in concert.