Задать заголовкам h2 автоматически id

<script>
document.addEventListener("DOMContentLoaded", function () {
  const toc = document.getElementById("toc");
  const headers = document.querySelectorAll("h2");
  const ul = document.createElement("ul");

  headers.forEach((header, index) => {
    const anchorId = "section-" + (index + 1);
    header.setAttribute("id", anchorId);

    const li = document.createElement("li");
    const a = document.createElement("a");
    a.href = "#" + anchorId;
    a.textContent = header.textContent;
    li.appendChild(a);
    ul.appendChild(li);
  });

  toc.appendChild(ul);
});
</script>