What's new

Web HTML to in memory representation

  • Thread starter NukeZilla
  • Start date
  • Views 239
N

NukeZilla

Enthusiast
Messages
144
Reaction score
40
Hi

SO i'm in the process of of creating a strip back run time virtual dom which allows you to only monitor whats need. As part of the first times I needed to clone the dom into an in memory object. To do this I imported my unflatteren located here. Next step was to read the dom node and put it into an easy to dif in memory object.

Code:
import {unflatten} from './utilities/unflatten'
function htmlToJson (node) {
    let jsonHtml = [];
  function Guid() {
      function S4() {
          return (((1+Math.random())*0x10000)|0).toString(16).substring(1); 
      }
        return (S4() + S4() + "-" + S4() + "-4" + S4().substr(0,3) + "-" + S4() + "-" + S4() + S4() + S4()).toLowerCase();   
  }
  function toHtml(node, parent = null) {
      for (var value of node.childNodes) {
 
      const id = Guid();
      if(value.nodeName !== '#text') {
        const attr = document.createAttribute("gjs-vid");
        attr.value = id;
        value.setAttributeNode(attr);
      }
      jsonHtml.push({ 
          'id': id,
          'parentId': parent,
          'node': value.nodeName,
          'props': value.attributes == null ? null : Array.prototype.slice.call(value.attributes).map((item) => {return {'name': item.name, 'value': item.value}}),
          'value': value.nodeValue === null ? null : value.nodeValue.trim()
       });
      if (value.childNodes.length > 0) {
        toHtml(value, id);
      }
      }
  }
  toHtml(node);
  return unflatten(jsonHtml);
}

export {htmlToJson}

I'm still currently implementing a dif checker and other features as part of an on going project. However thought it was extremely useful as it adds an data attribute called 'gjs-vid' which is unique so it's easy to query for the element.

Kind regards,
Jordan
 
Top Bottom