Morphing One DOM Tree To Another – idiomorph

Category: Javascript | September 13, 2022
Views Total:22 views
Official Page:Go to website
Last Update:September 13, 2022


Morphing One DOM Tree To Another – idiomorph


Yet another DOM merging library that allows you to morph one DOM tree to another.

Inspired by the morphdom library, which is a lightweight module for morphing an existing DOM node tree to match a target DOM node tree.


Both morphdom and nanomorph use the id property of a node to match up elements within a given set of sibling nodes. When an id match is found, the existing element is often not removed from the DOM, but is morphed in place to the new content. This preserves the node in the DOM and allows state (such as focus) to be retained. However, in both these algorithms, the structure of the children of sibling nodes is not considered when morphing two nodes: only the ids of the nodes are considered. This is due to performance considerations: it is not feasible to recurse through all the children of siblings when matching things up.

idiomorph takes a slightly different approach: before node-matching occurs, both the new content and the old content are processed to create id sets, a mapping of elements to a set of all ids found within that element. That is, the set of all ids in all children of the element, plus the elements’ id, if any.

id sets can be computed relatively efficiently via a query selector + a bottom up algorithm.

Given an id set, you can now adopt a broader sense of “matching” than simply using id matching: if the intersection between the id sets of element 1 and element 2 is non-empty, they match. This allows idiomorph to relatively quickly match elements based on structural information from children, who contribute to a parents id set, which allows for better overall matching when compared with id-based matching.

How to use it:

1. Download and load the idiomorph.js in the document.

<script src="/path/to/src/idiomorph.js"></script>

2. Morph the existing node to another.

Idiomorph.morph(existingNode, newNode);


v0.0.7 (09/13/2022)

  • clean up findSoftMatch()

You Might Be Interested In:

Leave a Reply