Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse header (<h1> -- <h6> tags) to ordered list, using jQuery?

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:

  • lorem
    • ipsum
    • dolor
      • sit
    • amet

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?

like image 451
modernserf Avatar asked Jul 02 '13 07:07

modernserf


1 Answers

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))

like image 148
alex_wdmg Avatar answered Oct 13 '22 01:10

alex_wdmg