Convert JSON to HTML Tree

前端 未结 6 1746
悲&欢浪女
悲&欢浪女 2020-12-13 16:03

I would like to generate an HTML tree (preferably UL-LI) from the JSON example below. Does anyone have a simple, recursive JS function (not a framework) tha

6条回答
  •  盖世英雄少女心
    2020-12-13 16:28

    function to_ul (obj) {
      // --------v create an 
      element var f, li, ul = document.createElement ("ul"); // --v loop through its children for (f = 0; f < obj.folder.length; f++) { li = document.createElement ("li"); li.appendChild (document.createTextNode (obj.folder[f].title)); // if the child has a 'folder' prop on its own, call me again if (obj.folder[f].folder) { li.appendChild (to_ul (obj.folder[f].folder)); } ul.appendChild (li); } return ul; }

    Caveat: No error checking! If a 'title' or 'folder' is missing, the whole thing could blow up.

提交回复
热议问题