I'm making a table of contents, in the style of an ordered list, based on the header structure, such that:
<h1>lorem</h1>
<h2>ipsum</h2>
<h2>dolor</h2>
<h3>sit</h3> 
<h2>amet</h2>
becomes:
This is how i'm currently doing it:
$('h1, h2, h3, h4, h5, h6').each ()->
  # get depth from tag name
  depth = +@nodeName[1]
  $el = $("<li>").text($(this).text())
  do get_recursive_depth = ()->
    if depth is current_depth
      $list.append $el
    else if depth > current_depth
      $list.append( $("<ol>") ) unless $list.children().last().is('ol')
      $list = $list.children().last()
      current_depth += 1
      get_recursive_depth()
    else if depth < current_depth
      $list = $list.parent()
      current_depth -=1
      get_recursive_depth()
which works, but it seems like it lacks elegance. Is there a smarter / faster / more robust way to do this?
jQuery emplementation:
var $el, $list, $parent, last_depth;
$list = $('ol.result');
$parent = [];
$parent[1] = $list;
last_depth = 1;
$el = 0;
$('h1, h2, h3, h4, h5, h6').each(function () {
    var depth;
    depth = +this.nodeName[1];
    if (depth > last_depth) {
        $parent[depth] = $('<ol>').appendTo($el);
    }
    $el = $("<li>").text($(this).text());
    $parent[depth].append($el);
    return last_depth = depth;
});
Maybe someone will come in handy))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With