When and how should you use lwc:dom="manual" for programmatic DOM manipulation?
Answer
Basics: LWC owns its DOM and normally forbids manual DOM edits inside the template, because they would conflict with its diffing. When a library such as a charting or map tool wants to draw into a container, you mark the container as manually managed so the engine stays out of it.
How it works:
- Add
<div lwc:dom="manual" class="host"></div>in the template. - In JS, after render (usually in a guarded
renderedCallback), get it withthis.template.querySelector('.host'). - Insert nodes:
el.appendChild(node)or setel.innerHTML, or pass the element to a third-party library. - The engine ignores the children you add and does not remove or diff them.
Advanced / deep dive: The directive is only valid on native elements (for example div, span), not on custom or base components and not on <template>. Elements added manually are not scoped to the component's CSS in synthetic shadow, so style them inline, via the library, or with global/static resource CSS; this is a frequent surprise. Inserting HTML strings creates an XSS risk: only insert trusted or sanitized content, and note that Lightning Web Security or Locker may restrict or sanitize some operations. For displaying rich text from fields use lightning-formatted-rich-text, which sanitizes. You are responsible for cleanup: remove nodes and destroy library instances in disconnectedCallback to avoid leaks. Because the engine will not re-render the manual region, you must update it yourself when data changes, usually in renderedCallback guarded by a flag or when a setter runs. Prefer native LWC templates whenever possible; this is an escape hatch.
Code / config example: