How create anchor link for each heading at the page?

Hello there. I have a js code, that looking for all h1-h6 tags per page and add to them a anchors, that i make from id attribute of h-tag.

(function() {
  const h1 = Array.from(document.querySelectorAll('h1'));
  const h2 = Array.from(document.querySelectorAll('h2'));
  const h3 = Array.from(document.querySelectorAll('h3'));
  const h4 = Array.from(document.querySelectorAll('h4'));
  const h5 = Array.from(document.querySelectorAll('h5'));
  const h6 = Array.from(document.querySelectorAll('h6'));
  let arr = [h1, h2, h3, h4, h5, h6];
  arr = arr.flat();

  function copyLink(e) {    
    e.preventDefault();
    const url = new URL(window.location.href);
    url.hash = '';
    navigator.clipboard.writeText(`${url.href}${e.target.getAttribute('href')}`);
  }

  for(let h of arr) {
    const span = document.createElement('span');
    span.textContent = h.textContent;
    h.textContent = '';
    h.appendChild(span);
    const a = document.createElement('a');
    a.href = '#' + h.id;
    span.appendChild(a);
    a.addEventListener('click', copyLink);
  }
})();

This code is implemented on the frontend. After the page loads and the script runs.
I want to implement such code in hugo. So that all anchor links are ready at the site assembly stage, and the user uploads them as a finished part of the html page. Hugo has a plugin for this? I see how to do it in node js, but I don’t know how to do it in hugo.
And I would like to select pages for which this code will work (like a selector in js).

1 Like

See https://gohugo.io/templates/render-hooks/.

You can control which pages are affected in (a) front matter with boolean param, and/or (b) site configuration (array of paths, a regex to match paths, etc.).