JSFiddle - React, Tailwind, and code Playground

by jrunning

JavaScript

function buildTree(node, depth = 0) {
  if (!(i--)) {
  	throw new Error('Oops got out of hand');
  }
  if ('rawText' in node) {
  	return node.rawText;
  }
  const indent = ' '.repeat(depth * 2);
  let str = `${indent}<${node.tagName}`;
  if (node.childNodes && node.childNodes.length !== 0) {
    const nextNodes = node.childNodes.map(child =>
    	buildTree(child, depth + 1));
    
  	str = `${str}>
${nextNodes.join()}
${indent}</${node.tagName}>`;
  } else {
  	str = `${str}/>`;
  }
  return str;
}

const tree = {
		tagName: 'body',
    childNodes: [
        {
            tagName: 'div',
            childNodes: [
                {
                    tagName: 'span',
                    childNodes: [
                        {
                             rawText: 'My Content'
                        }
                    ],
                }
            ]
        }
    ]
};

console.log(buildTree(tree));