javascript - Produce heading hierarchy as ordered list -


I am considering this for a while but the task can not come with the solution. I can not even do psuedo code ...

For example, you have a page with such title structure:

  & lt; H1 & gt; Title Level 1 & lt; / H1> & Lt; H2 & gt; Sub Title # 1 & lt; / H2 & gt; & Lt; H2 & gt; Sub title # 2 & lt; / H2 & gt; & Lt; H3 & gt; Sub sub title & lt; / H3 & gt; & Lt; H2 & gt; Sub title # 3 & lt; / H2 & gt; & Lt; H3 & gt; Sub sub title # 1 & lt; / H3 & gt; & Lt; H3 & gt; Sub sub title # 2 & lt; / H3 & gt; & Lt; H4 & gt; Sub sub sub title & lt; / H4 & gt; & Lt; H2 & gt; Sub title # 4 & lt; / H2 & gt; & Lt; H3 & gt; Sub sub title & lt; / H3 & gt; Using javascript (any outline is ok), how will you go about preparing a list like this (with nested lists)  
   

Every time I try and start with a certain methodology that makes it very bloated.

Solution Crossing each title and putting it in its proper nested list - I keep repeating it myself, but I can not write anything!

Even if you have a workflow in your head, but I do not have time to code it, I still want to know it! :)

Thank you!

First, build a tree. Pseudocode (because I'm not fluent in JavaScript):

  var titles = array (...); Var tree level = array (); Var treeRoots = array (); Leading (titles in the form of headings) {if (heading.level == tree lit. length) {/ * near siblings * / if (heading.level == 1) {treeRoots [] = title; // Attach} other {tree levels [tree leave. Length - 2]. Children [] = title; // Add the child to the basic element. } Tree level [tree live. Long - 1] = heading; } And if (heading.level> gt; treeLevels.length) {/ * child * / while (heading.level - 1> treeLevels.length) {/ * if necessary make dummy headings * / tree level [ ] = New heading (); } Tree Lilies [] = Title; } Other {/ * Ancestors Child * / Tree Level Remove (heading level, tree level. Length - 1); Tree level [Tree leaved. Lengthy - 1]. Children [] = title; Tree level [] = title; }}  

Next, we index it, to create the list.

  function buildList (root) {var le = new LI (root.text); If (root.children.length) {var subl = new ul (); Li.children [] = Subuel; Forrest (child as the child.) {SubUl. Children [] = buildlist (kids); }} Returned; }  

Finally, enter ul back buildList in ul for each treeRoots < / Code>.

In jQuery, you can move header elements in order such as:

  var header = $ ('*'). Filter (function () {Return.tagName.match (/ h \ d / i);}) ();  

Comments