Blog>
Snippets

Incremental DOM - Basic Element Patching

Demonstrate how to selectively update elements in the DOM using Angular's Incremental DOM patch function.
import { patch, elementOpen, elementClose, text } from 'incremental-dom';

function render(data) {
  elementOpen('div', null, ['id', 'my-div']);
  text(data.text);
  elementClose('div');
}

// The object we'll use to represent our DOM
const el = document.getElementById('patchable-container');

// Our data model
const data = { text: 'Hello, Incremental DOM!' };

// Initial rendering
patch(el, () => render(data));
This imports the required functions from Incremental DOM and defines a render function that creates a div element with text from the data object. The `patch` function applies the `render` function to the specified element, 'patchable-container', which is the initial rendering of our DOM.
// Update the data model
data.text = 'Updated text!';

// Apply the changes to the DOM
patch(el, () => render(data));
Updates the data object with new text and then applies the revised render function to 'patchable-container' using the `patch` function. Incremental DOM efficiently updates only what has changed.