Sobes.tech
Middle+

What are the differences between Shadow DOM, Virtual DOM, and regular DOM?

sobes.tech AI

Answer from AI

Shadow DOM creates an isolated DOM tree inside an element, hiding its internal structure from the main document. This is useful for encapsulating styles and component behavior.

Virtual DOM is a lightweight representation of the real DOM in memory, used by React (and other libraries) to optimize updates. Changes are first applied to the Virtual DOM, then compared with the previous state (diffing), and only minimal changes are applied to the real DOM (patching).

The regular DOM is an object-oriented representation of the HTML document, provided by the browser for manipulating the structure, styles, and content of the page using JavaScript. Direct modifications to a large and complex regular DOM can be slow.

Here's a brief comparison:

Feature Shadow DOM Virtual DOM Regular DOM
Purpose Encapsulation Update optimization Document representation
Nature Part of browser API Concept/library-based Part of browser API
Manipulation Via Shadow Root API Via libraries (React) Directly via JS API
Performance Improves isolation, may be slower with many nested Shadow DOMs Improves performance by minimizing direct DOM operations Direct changes can be slow

Example of using Shadow DOM:

<script>
  const host = document.getElementById('my-component');
  const shadowRoot = host.attachShadow({ mode: 'open' }); // Create Shadow DOM
  shadowRoot.innerHTML = `
    <style>
      p {
        color: blue; /* This style applies only inside Shadow DOM */
      }
    </style>
    <p>Hello from Shadow DOM!</p>
  `;
</script>

<div id="my-component"></div>
<p style="color: red;">This text is red, style from Shadow DOM does not affect it.</p>