jQuery – How to automatically create heading anchors for links

The following jQuery can be used to automatically create anchor tags for each of the headings on a web page.

This will allow you to create links directly to each of the headings on the page.

For example, a heading titled ‘Heading 1’ on page www.domain.com/page/ would change from

<h1>Heading 1</h1>


<h1 id='heading 1'>Heading 1</h1>

You could then link directly to Heading 1 using the link

www.domain.com/page/#heading 1

The jQuery will:

  • load once the page has finished loading
  • target heading level H1 to H6 in the article tag (you may have to change this to suit your website)
  • take each of the headings and create an anchor using the lower-case text (and trim any white space to the left or right, as well as remove punctuation that may break anchor links, such as a question mark)

Please note: if you’re using this in WordPress you will need to replace the dollar symbols ($) with the word jQuery.

$(document).ready(function() {
$("article h1, article h2, article h3, article h4, article h5, article h5").each(function(i) {
 var heading = $(this);
 var headingtext = heading.text().toLowerCase().trim().replace(/[\.,-\/#!?$%\^&\*;:{}=\-_`~()]/g,"");
 heading.attr("id",headingtext );