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

后端 未结 12 1721
广开言路
广开言路 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:00

     let headers = document.querySelectorAll('h1,h2,h3,h4,h5,h6');
      let list    = document.createElement('ol');
    
      let _el = list;
      for(i=0; i 0 ? ol = _el.querySelector('ol') : document.createElement('ol');
            ol.appendChild(li);
            _el.appendChild(ol);
            _el = li;
            break;
          } else {
            if(_el.tagName == 'OL') {
             _el.appendChild(li);
             _el = li;
             break;
            } else if (!_el.parentNode.parentNode) {
              _el.parentNode.appendChild(li);
              _el = li;
              break;
            }
            else {
              _el = _el.parentNode.parentNode;
            }
          }
        }
      }
      console.log(list);
    

提交回复
热议问题