Skip to content Skip to sidebar Skip to footer

Recursion In Function Creating DOM Tree

Good people, explain to me, please work this function: function createTreeDom(obj) { if (isObjectEmpty(obj)) return; var ul = document.createElement('ul'); for (var key in

Solution 1:

It creates nested lists using nested objects. In one level nesting, it creates a single level simple ul li, li ... list. But if some value is non-empty object like this

var arg = { "one":{}, "two":{}, "three":{"subone":{}, "subtwo":{}}, "four":{}};

then the subobject is appended as the sublist in the recursion

var childrenUl = createTreeDom(obj[key]);
if (childrenUl) li.appendChild(childrenUl);

If the value is not empty object, no sublist is created, since there is a stop condition as the first command:

if (isObjectEmpty(obj)) return;

Step by step for the array above: for the first item, the function creates ul element and adds li into it, with the key="one" and obj[key]={}:

<ul>
  <li>one</li>
</ul>

But it is not done yet, now the recursion is called: createTreeDom({}). Since isObjectEmpty({}) (obviously) returns true, the recursion ends and childrenUl is undefined. Therefore, no contents is added to li and the cycle jumps to the second node, which is also just a simple string literal, so it adds another li node:

<ul>
  <li>one</li>
  <li>two</li>
</ul>

Now the point: the third argument. Before the execution goes to the recursion, it looks like this:

<ul>
  <li>one</li>
  <li>two</li>
  <li>three</li>
</ul>

But the value of the third member is not an empty object, so the command

if (childrenUl) li.appendChild(childrenUl);

creates an ul node filled with its contents step by step like above and appends it to the li element:

<ul>
  <li>one</li>
  <li>two</li>
  <li>three
    <ul>
      <li>subone</li>
      <li>subtwo</li>
    </ul>
  </li>
</ul>

If some of the nested item contained another non-empty object, it would be appended as sub-sub list to some sub-list li and so on.

There could be better to read equivalent:

function createTreeDom(obj) {
  var ul = document.createElement('ul');

  for (var key in obj) {
    var li = document.createElement('li');
    li.innerHTML = key;

    if (!isObjectEmpty(obj[key])) {
      var childrenUl = createTreeDom(obj[key]);
      li.appendChild(childrenUl);
    }

    ul.appendChild(li);
  }

  return ul;
}

Post a Comment for "Recursion In Function Creating DOM Tree"