FrontendInterviews.dev

Loading problem…

17. Virtualize DOM Tree

Medium•
Acceptance: 55.56%
•
🔓3/3 Pro unlocks today

You're building a virtual DOM system similar to React. The first step is to convert a real DOM tree into an object literal representation that can be serialized, manipulated, and later rendered back to DOM.

Given a real DOM element, convert it to an object literal representation similar to how React represents JSX elements. This process is called "virtualization" - creating a virtual representation of the DOM.

Requirements

1. Basic Functionality

  • Convert DOM elements to objects with type and props structure
  • Handle text nodes as strings
  • Support single child and multiple children
  • Convert HTML attributes to camelCase properties (e.g., class → className, data-test → dataTest)
  • Preserve all standard HTML attributes

Example Usage

// Given this DOM structure:
// <div>
//   <h1>Hello</h1>
//   <p class="text">World</p>
// </div>

const element = document.querySelector('div');
const virtual = virtualize(element);

// Returns:
// {
//   type: 'div',
//   props: {
//     children: [
//       {
//         type: 'h1',
//         props: { children: 'Hello' }
//       },
//       {
//         type: 'p',
//         props: {
//           className: 'text',
//           children: 'World'
//         }
//       }
//     ]
//   }
// }

Real-World Context

This problem models real virtual DOM systems:

  • React: JSX is transformed to object literals like this
  • Vue: Creates virtual nodes for rendering
  • State management: Serialize DOM state for persistence
  • Testing: Convert DOM to testable object structures
  • Diffing algorithms: Virtual DOM enables efficient updates

Constraints

  • Handle standard HTML elements only
  • Support text nodes as string children
  • Convert HTML attributes to camelCase (class → className, for → htmlFor, etc.)
  • Handle single child (not wrapped in array)
  • Handle multiple children (wrapped in array)
  • Ignore event handlers and non-standard properties
  • Handle empty elements (no children)