Below is a simple Virtual DOM implementation in JavaScript. This example shows how to:
Define virtual nodes using a helper function (h) that creates virtual node objects.
Create real DOM elements from virtual nodes using a createElement function.
Diff and patch the differences between two virtual DOM trees onto the real DOM using an updateElement function.
Below is the complete code with detailed comments and step-by-step explanations.
1. Defining a Virtual Node
We start by defining our virtual node “structure.” In this example, a virtual node is simply an object with a tag name, optional properties, and an array of children.
js
// A helper function to create a virtual node (vnode)
// tag: the HTML tag name (e.g., 'div')
// props: an object containing attributes/props (e.g., { id: 'myDiv' })
// children: an array containing either strings (text nodes) or other virtual nodes
function h(tag, props, children) {
return { tag, props: props || {}, children: children || [] };
}
2. Rendering a Virtual Node to Real DOM
The createElement function takes a vnode and creates the corresponding real DOM element. This involves setting attributes from props and recursively rendering any child nodes.
js
// Recursively creates a real DOM element from a virtual node
function createElement(vnode) {
// If the vnode is a string, we assume it's a text node
if (typeof vnode === "string") {
return document.createTextNode(vnode);
}
// Create the element based on the vnode's tag
const el = document.createElement(vnode.tag);
// Set properties/attributes
for (let prop in vnode.props) {
el.setAttribute(prop, vnode.props[prop]);
}
// Create and append each child (which may be a virtual node or a text node)
vnode.children.forEach(child => {
el.appendChild(createElement(child));
});
return el;
}
3. Diffing and Patching
We want to update our actual DOM when our virtual DOM changes. There are three main tasks:
Adding new nodes.
Removing nodes that no longer exist.
Updating nodes that have changed.
Helper: Check if Nodes Have Changed
This function checks if two nodes are fundamentally different:
If they are of different types.
If they are strings (text nodes) and have different values.
The updateElement function compares an old virtual node and a new virtual node, then applies the minimum number of changes to the real DOM.
js
/**
* Update the real DOM element based on differences between newVNode and oldVNode.
*
* parent: the real DOM parent node.
* newVNode: the new virtual node.
* oldVNode: the old virtual node.
* index: the position of the node in the parent's childNodes.
*/
function updateElement(parent, newVNode, oldVNode, index = 0) {
// Case 1: There was no old node, so add the new node.
if (!oldVNode) {
parent.appendChild(createElement(newVNode));
// Case 2: There is no new node, so remove the old node.
} else if (!newVNode) {
parent.removeChild(parent.childNodes[index]);
// Case 3: The nodes have changed, so replace the old with the new.
} else if (changed(newVNode, oldVNode)) {
parent.replaceChild(createElement(newVNode), parent.childNodes[index]);
// Case 4: Both nodes are the same type, so update their properties and children.
} else if (newVNode.tag) {
// Update attributes (properties)
updateProps(parent.childNodes[index], newVNode.props, oldVNode.props);
// Get the maximum number of children between the old and new vnodes
const newLength = newVNode.children.length;
const oldLength = oldVNode.children.length;
for (let i = 0; i < newLength || i < oldLength; i++) {
updateElement(
parent.childNodes[index],
newVNode.children[i],
oldVNode.children[i],
i
);
}
}
}
Update Properties
The updateProps function compares and updates the attributes on a real DOM element, removing old attributes and adding or updating new ones.
js
function updateProps(realDom, newProps, oldProps) {
// Combine props keys from both old and new objects
for (let key in { ...oldProps, ...newProps }) {
const newVal = newProps[key];
const oldVal = oldProps[key];
if (!newVal) {
realDom.removeAttribute(key);
} else {
if (newVal !== oldVal) {
realDom.setAttribute(key, newVal);
}
}
}
}
4. Example Usage
Below is an example that creates an initial virtual DOM, renders it, and then updates it with a new virtual DOM.
js
// Initial Virtual DOM: a simple tree with a title and a list
const vdom1 = h("div", { id: "app" }, [
h("h1", { class: "title" }, ["Virtual DOM Example"]),
h("ul", {}, [
h("li", {}, ["Item 1"]),
h("li", {}, ["Item 2"]),
h("li", {}, ["Item 3"])
])
]);
// Render the initial virtual DOM and add it to the real DOM
const root = document.getElementById("root");
root.appendChild(createElement(vdom1));
// Updated Virtual DOM: change the title and modify the list
const vdom2 = h("div", { id: "app" }, [
h("h1", { class: "title" }, ["Updated Virtual DOM Example"]),
h("ul", {}, [
h("li", {}, ["Item 1"]),
h("li", {}, ["Item 2 updated"]),
// Remove the third item and add a new one
h("li", {}, ["Item 4"])
])
]);
// After some delay, update the real DOM with our diff/patch function
setTimeout(() => {
updateElement(root, vdom2, vdom1);
}, 2000);
Explanation of Example:
Building vdom1:
We create an initial virtual DOM with a <div> that contains an <h1> and a <ul> with three list items.
Rendering:
We then render vdom1 into the real DOM by calling createElement and appending it under the element with id="root".
Building vdom2 (Updated Virtual DOM):
We create another virtual DOM (vdom2) that changes the title, updates one list item, removes one, and adds another.
Patching:
After a short delay (2 seconds), updateElement is called to patch the existing DOM using the differences between vdom1 (the old state) and vdom2 (the new state).
Summary
Virtual Nodes Representation:
We represent each node as an object with a tag, props, and children.
Creating Real DOM:
The createElement function turns a virtual node into an actual DOM node recursively.
Diffing and Patching:
The updateElement function compares two virtual nodes, decides whether to remove, replace, or update a node, and then applies those changes to the real DOM.
This simple implementation demonstrates the basic ideas behind more sophisticated libraries like React or Virtual DOM libraries such as Snabbdom. It abstracts away native DOM manipulation into higher-level operations, improving performance by updating only the parts of the DOM that changed.