Is there a JavaScript solution to generating a “table of contents” for a page?

后端 未结 12 1729
广开言路
广开言路 2020-12-12 17:21

I have headers in

through
tags. Is there a way that I can use JavaScript to generate a table of contents for the contents tha

12条回答
  •  悲哀的现实
    2020-12-12 18:02

      this.insert = (el, h) => {
        let li = document.createElement('li');
        li.innerText = h.innerText;
        li.setAttribute('tagName', h.tagName);
        if(el.tagName == 'OL') {
          el.appendChild(li);
          return li;
        } else if(el.getAttribute('tagName') < h.tagName) {
          let ol = el.children.length > 0 ? ol = el.querySelector('ol') : document.createElement('ol');
          ol.appendChild(li);
          el.appendChild(ol);
          return li;
        } else if(!el.parentNode.parentNode) {
          el.parentNode.appendChild(li);
          return li;
        } else {
          return this.insert(el.parentNode.parentNode, h);
        }
      }
    
      this.parse = (headers) => {
        let list = document.createElement('ol');
        let el = list;
        for(i=0; i

提交回复
热议问题