Recent searches


No recent searches

Christian Espinosa's Avatar

Christian Espinosa

Joined Aug 20, 2024

·

Last activity Aug 20, 2024

Following

0

Followers

0

Total activity

2

Votes

0

Subscription

1

ACTIVITY OVERVIEW

Latest activity by Christian Espinosa

Christian Espinosa commented,

Community comment Discussion - Tips and best practices from the community

I wanted to contribute to this and provide an up to date version of the original js code without the fragility of regex, onload and var.

document.addEventListener('DOMContentLoaded', function() {
  const tocContainer = document.getElementById('toc');
  const contentContainer = document.getElementById('contents');

  function generateTableOfContents() {
    const headings = contentContainer.querySelectorAll('h1, h2, h3, h4, h5, h6');
    let currentLevel = 0;
    let tableOfContents = '';

    headings.forEach((heading) => {
      const headingLevel = parseInt(heading.tagName.charAt(1));
      const headingText = heading.textContent.trim();
      const headingId = headingText.replace(/\s/g, '_');

      heading.id = headingId;

      if (headingLevel > currentLevel) {
        tableOfContents += '
    '; } else if (headingLevel < currentLevel) { tableOfContents += '
'.repeat(currentLevel - headingLevel); } tableOfContents += `
  • ${headingText}
  • `; currentLevel = headingLevel; }); if (currentLevel > 0) { tableOfContents += ''.repeat(currentLevel); } tocContainer.innerHTML = tableOfContents; } generateTableOfContents(); });

     

    Best,

    Christian

    View comment · Posted Aug 20, 2024 · Christian Espinosa

    0

    Followers

    0

    Votes

    0

    Comments