You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

目录(TOC)功能在标题标签包含class或id时失效的解决方案咨询

Fixing Table of Contents to Recognize Headings with Attributes

Got it, let's sort out this issue—your table of contents code is missing headings with attributes because the regex is too strict. It only matches <hX> tags that have no extra properties attached, which is why your <h1 class="test" id="myid"> gets skipped.

The Root Cause

The original regex /<h([\d])>([^<]+)<\/h([\d])>/gi expects the opening <hX> tag to immediately close with > right after the heading number. Any attributes like class or id break this pattern, so those headings get ignored.

The Simple Fix: Update the Regex

We just need to adjust the regex to allow any attributes inside the opening <hX> tag. Add [^>]* after the heading number—this matches any characters except >, covering all possible attributes (or no attributes at all).

Here's the modified full code:

document.addEventListener('DOMContentLoaded', function() { TableOfContents(); } );
function TableOfContents() {
 var toc = "";
 var level = 0;
 var container = document.querySelector(container) || document.querySelector('#contents');
 var output = output || '#toc';
 container.innerHTML = container.innerHTML.replace(
 // Updated regex to support headings with attributes
 /<h([\d])[^>]*>([^<]+)<\/h([\d])>/gi,
 function (str, openLevel, titleText, closeLevel) {
 if (openLevel != closeLevel) {
 return str;
 }
 if (openLevel > level) {
 toc += (new Array(openLevel - level + 1)).join('<ul>');
 } else if (openLevel < level) {
 toc += (new Array(level - openLevel + 1)).join('</li></ul>');
 } else {
 toc += (new Array(level+ 1)).join('</li>');
 }
 level = parseInt(openLevel);
 var anchor = titleText.replace(/ /g, "_");
 toc += '<li><a href="#' + anchor + '">' + titleText + '</a>';
 return '<h' + openLevel + '><a href="#' + anchor + '" id="' + anchor + '">' + titleText + '</a></h' + closeLevel + '>';
 }
 );
 if (level) {
 toc += (new Array(level + 1)).join('</ul>');
 }
 document.querySelector(output).innerHTML += toc;
};

What Changed?

The critical adjustment is in the regex:

  • Original: /<h([\d])>([^<]+)<\/h([\d])>/gi
  • Modified: /<h([\d])[^>]*>([^<]+)<\/h([\d])>/gi

The [^>]* segment tells the regex to accept any content (like class="test" id="myid") between the hX and the closing > of the opening tag.

Testing with Your Example

Now when you run this code against your sample HTML, all three headings—including the one with class and id—will be correctly detected and added to the table of contents.

内容的提问来源于stack exchange,提问作者AdityaDees

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 23:17:45