Skip to content

Instantly share code, notes, and snippets.

@anonystick
Created June 17, 2021 11:07
Show Gist options
  • Save anonystick/6fc7bb2db0a19415747c86da7ed8c013 to your computer and use it in GitHub Desktop.
Save anonystick/6fc7bb2db0a19415747c86da7ed8c013 to your computer and use it in GitHub Desktop.
var $=function(){"use strict";var e=function(e){this.elems="document"===e?[document]:"window"===e?[window]:document.querySelectorAll(e)};e.prototype.createMenuItem=function(e){let t=document.createElement("li");return t.style="list-style-type: circle",t.innerHTML=e,t},e.prototype.init=function(e){self=this;let t="h2",n=document;e.headingSelector&&(t=e.headingSelector),e.contentSelector&&(n=document.querySelector(e.contentSelector)),console.log("h2:::",t),this.each(function(e){const o=self.getElementsByTagNames(t,n);if(console.log("::toBeTOCced::",o.length),o.length>0)for(let t=0;t<o.length;t++){const n=o[t],r=n.textContent;n.id=`${r}`;let c=`<a href="#${r}">${r}</a>`;e.appendChild(self.createMenuItem(c))}})},e.prototype.each=function(e){if(e&&"function"==typeof e)for(var t=0;t<this.elems.length;t++)e(this.elems[t],t)},e.prototype.getElementsByTagNames=function(e,t){for(var n=e.split(","),o=new Array,r=0;r<n.length;r++)for(var c=t.getElementsByTagName(n[r]),l=0;l<c.length;l++)o.push(c[l]);var i=o[0];return i?(i.sourceIndex?o.sort(function(e,t){return e.sourceIndex-t.sourceIndex}):i.compareDocumentPosition&&o.sort(function(e,t){return 3-(6&e.compareDocumentPosition(t))}),o):[]};return function(t){return new e(t)}}();$("#toc").init({contentSelector:"#content-body",headingSelector:"h1,h2,h3"});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment