User:Hippietrail/addstructure.js

From Wiktionary, the free dictionary
Jump to navigation Jump to search

Note – after saving, you may have to bypass your browser’s cache to see the changes.

  • Mozilla / Firefox / Safari: hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (Command-R on a Macintosh);
  • Konqueror and Chrome: click Reload or press F5;
  • Opera: clear the cache in Tools → Preferences;
  • Internet Explorer: hold Ctrl while clicking Refresh, or press Ctrl-F5.

// Make the article's DOM structure reflect the wikisource heading structure
 
function addstructure() {
 
  if (wgNamespaceNumber != 0) return;
 
  var bc = document.getElementById('bodyContent');
 
  if (bc) {
    for (var l = 6; l >= 2; l--) {
      var headings = bc.getElementsByTagName('h' + l.toString());
 
      for (var i = 0; i < headings.length; i++) {
        var h = headings[i];
 
        // yuck - special cases
        if (h.previousSibling == null || h.firstChild.nodeType == 3) continue;  // Preview h2
        if (h.parentNode.id == 'toctitle') continue;                            // TOC h2
        if (h.id == 'siteSub') continue;                                        // h3
 
        var prev = h.previousSibling.previousSibling;
        var next = h.nextSibling.nextSibling;
 
        var div = document.createElement('div');
        div.className = toclassname(prev.getElementsByTagName('a')[0].id);
        var parent = h.parentNode;
        parent.replaceChild(div, prev);
        div.appendChild(prev);
        div.appendChild(h);
 
        while (next) {
          // reparent text nodes and html elements
          // stop when we find the next section heading which is a P followed by an H
          if ((next.nodeType != 1 && next.nodeType != 3) ||
            (next.tagName == 'P' && next.nextSibling && next.nextSibling.nextSibling && next.nextSibling.nextSibling.nodeName.match(/^H[2-6]$/)))
            break;
 
          var nextnext = next.nextSibling;
 
          div.appendChild(next);
 
          next = nextnext;
        }
      }
    }
  } 
}
 
function toclassname(n) {
  return n.toLowerCase().replace(/[ _]+\d+$/, '').replace(/[ _]+/g, '-');
}