Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
* Enhances headers with names of parent headers
* If you have h2: 'abc' and h3: 'def', then h3 will be displayed as 'abc > def'
*
* @param {string} sectionSelector - id or class of the section that contains the headings, e.g. '#main'
* @param {number[]} headings - array of heading numbers that should be changed, in the order of processing, e.g.:
* [4, 3] -> for h4 show h3, for h3 show h2
* [3, 4] -> for h3 show h2, for h4 show h3 with h2
* @param {string} separator - the text between parent and child commit, by default it's '>'
* @param jQuery - reference to the jQuery
*
* Style the result in .prev-title, e.g.:
* span.prev-title {
* opacity: 0.5;
* font-size: 90%;
* }
*/
function addParentHeadings(sectionSelector, headings, separator = ' > ', jQuery = $) {
headings.forEach(function(level) {
jQuery(sectionSelector + ' h' + level).each(function() {
const $this = jQuery(this);
const prev = $this.prevAll('h' + (level-1)).first().text();
$this.html('<span class="prev-title">' + prev + separator + '</span>' + $this.html());
});
});
}
span.prev-title {
opacity: 0.5;
font-size: 90%;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment