User:Hippietrail/addstructure.js

// 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, '-'); }