Observing Rendered DOM Nodes

Sam Thorogood has been looking into all kinds of changes that can happen to DOM Nodes:

This post will explain how to be notified when:

  • an element is added or removed from the DOM
  • the bounding box of an element changes (i.e., resizes)
  • an element moves around the page for any reason

Expect some ResizeObserver, IntersectionObserver, and MutationObserver sprinkled all over the post.

Observing rendered DOM nodes →

Related: On Twitter Denis Radin chimed in with his StyleObserver.js to track style changes.

How to write your own Virtual DOM

1-e1s_Zc_fVxL3i0un2ZNEtg

The main part of Virtual DOM can be written in less than ~50 lines of code. […] When we change something in our Virtual DOM Tree, we get a new Virtual Tree. Algorithm compares these two trees (old and new), finds differences and makes only necessary small changes to real DOM so it reflects virtual.

const a = (
  <ul>
    <li>item 1</li>
    <li>item 2</li>
  </ul>
);

const b = (
  <ul>
    <li>item 1</li>
    <li>hello!</li>
  </ul>
);

// Set content of #root to a
updateElement(document.getElementById('root'), a);

// Set content of #root to b
updateElement(document.getElementById('root'), b, a);

In the image above you can see what happens in the Virtual DOM when a is replaced by b (triggered by updateElement(document.getElementById('root'), b, a);). Only the childElement that is different is updated in the actual DOM.

How to write your own Virtual DOM: Part 1: The Basics →
How to write your own Virtual DOM: Part 2: Props & Events →