DEV Community

Shweta Kale
Shweta Kale

Posted on

DOM Question #6 - Serialization

Write code to serialize given HTML

Serialization means converting given HTML to JSON format. In the JSON we need to store node name, node type, children, props.

<div id="foo">
  <h1>Hello</h1>
  <p class="bar">
    <span>World!</span>
  </p>
</div>

Enter fullscreen mode Exit fullscreen mode

We will create a function and call it recursively on all HTML children to get JSON data in required format.

function getNodeProps(node){
  let props = {};
  for(let i=0; i< node.attributes.length; i++){
    const attribute = node.attributes[i];
    props[attribute.nodeName] = attribute.nodeValue;
  }
  return props;
}

function serialize(node){
  const serializedJSON = {};
  serializedJSON.nodeName = node.nodeName;
  serializedJSON.nodeType = node.nodeType;

  const props = getNodeProps(node);
  serializedJSON.props = props;

  let children = [];
  if(node.children.length>0){
   for(let i=0; i< node.children.length; i++){
    children.push(serialize(node.children[i]));
   }}
  serializedJSON.children = children;

  return serializedJSON;
}
Enter fullscreen mode Exit fullscreen mode

This will give us serialized JSON but what about time complexity?

Total time complexity: Since the function recursively visits every node in the tree, the total time complexity is proportional to the number of nodes and the number of attributes and children. In the worst case, the time complexity is:

O(N×(A+C))

Where:

  • N: is the total number of nodes.
  • A: is the average number of attributes per node.
  • C: is the average number of children per node.

Top comments (0)