User:Connel MacKenzie/custom.js/addstructure.js

Note: You may have to bypass your browser’s cache to see the changes. In addition, after saving a sitewide CSS file such as MediaWiki:Common.css, it will take 5-10 minutes before the changes take effect, even if you clear your cache.

  • 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.

/*
<pre>
*/
 
// 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.title = 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;
        }
      }
    }
  } 
}

addOnloadHook( addstructure ); 
/*
</pre>
*/